xGoPox
xGoPox

Reputation: 684

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 :)

Upvotes: 0

Views: 228

Answers (4)

FluffulousChimp
FluffulousChimp

Reputation: 9185

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.

Upvotes: 1

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

I suggest NSTimer + NSThred for your purpose

[NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(triggerTimer:) 
userInfo:nil repeats:YES];

-(void) triggerTimer:(NSTimer *)theTimer 
{
    //Here perform the thread operations
   [NSThread detachNewThreadSelector:@selector(myThreadMethod) toTarget:self withObject:nil];
}

Upvotes: 0

onevcat
onevcat

Reputation: 4631

You can try to use a NSTimer to implement it. Register a NSTimer in your main thread:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];

and you can have -doSomething to start a thread to do your actual work:

-(void) doSomething {
    dispatch_queue_t doThings = dispatch_queue_create("doThings", NULL);
    dispatch_async(doThings, ^{

       //Do heavy work here...

       dispatch_async(dispatch_get_main_queue(), ^{
           //Here is main thread. You may want to do UI affair or invalidate the timer here.
       });
   });
}

You can refer to NSTimer Class and GCD for more info.

Upvotes: 0

Popeye
Popeye

Reputation: 12123

You could set an NSTimer up that will run a method that starts your thread

  // Put in a method somewhere that i will get called and set up.
 [NSTimer timerWithTimeInterval:10 target:self selector:@selector(myThreadMethod) userInfo:nil repeats:YES];

or

  [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(myThreadMethod) userInfo:nil repeats:YES];

You can also set this to an NSTimer so you can set up the poroperties of the timer. Such as start and finish.

 - (void)myThreadMethod
 {
      [NSThread detachNewThreadSelector:@selector(someMethod) toTarget:self withObject:nil];
  }

Upvotes: 1

Related Questions