每隔“X”秒发射一次NSThread

时间:2012-12-07 10:04:30

标签: objective-c nstimer nsthread

我遇到NSThread的问题,我不太了解......

如何很好地创建NSThread:

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

...然后

我对NSThread和他的所有方法都有点混淆。

我想创建一个NSThread并每隔5分钟触发一次(当然继续使用我的应用程序:)

4 个答案:

答案 0 :(得分:1)

你可以设置一个NSTimer,它将运行一个启动你的线程的方法

  // 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];

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

您也可以将其设置为NSTimer,以便设置计时器的poroperties。如开始和结束。

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

答案 1 :(得分:1)

或者使用GCD调度源,因为Apple建议远离NSThread使用。

假设存在以下ivar:

dispatch_source_t _timer;

然后,例如:

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

将每隔2秒在后台队列上发起一个小任务,但余地很小。

答案 2 :(得分:0)

我建议将 NSTimer + NSThred 用于您的目的

[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];
}

答案 3 :(得分:0)

您可以尝试使用NSTimer来实现它。在主线程中注册NSTimer:

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

你可以让-doSomething开始一个线程来完成你的实际工作:

-(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.
       });
   });
}

您可以参考NSTimer ClassGCD了解详情。