objective-cnstimernsthread

Fire a NSThread every 'X' seconds


I'm having an issue with NSThread which I don't understand very well..

How to well create a NSThread:

- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument

then...

I'm a bit confuse with NSThread and all of his methods.

I want to create a NSThread and fire it every 5 minutes (and of course keep using my applications without latence :)


Solution

  • Or use a dispatch source with GCD since Apple is recommending migrating away from NSThread use.

    Assuming the following ivar exists:

    dispatch_source_t _timer;
    

    then, for example:

    dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, backgroundQueue);
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC, 0.05 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        NSLog(@"periodic task");
    });
    dispatch_resume(_timer);
    

    which will fire a small task on a background queue every 2 seconds with a small leeway.