2

I am trying to schedule NSTimer on a separate thread and this is how i am doing it.

-(void) startSpinner {
#ifdef DEBUG_MODE
    NSLog(@"Starting Spinner...");
#endif
    self.spinnerThread = [[[NSThread alloc] initWithTarget:self selector:@selector(scheduleSpinner) object:nil] autorelease];
    [spinnerThread start];
}

-(void) scheduleSpinner {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSTimer *_spinTimer = [NSTimer scheduledTimerWithTimeInterval:SPIN_FIRE_INTERVAL target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:_spinTimer forMode:NSRunLoopCommonModes];
    [runLoop addTimer:_spinTimer forMode:UITrackingRunLoopMode];
    [runLoop run];

    [pool release];
}

timerFireMethod spins my spinner and when a button is pressed (stop button), i invalidate the timer and exit the thread in this method. I do a polling here if spin button is pressed.

The problem is, my timerFireMethod gets called properly for the first time. Spinner spins for first time. But when i stop my spinner and start it again, spinner doesn't spins. The logs say that second time my "startSpinner" method gets called but "timerFireMethod" method is not called.

The worse is, the spinner works 5-6 times on simulator, 1 times on 2g device, 4-5 times on latest ipod. Its random.

How does this basically work? What could be the problem?

  • 2
    If only reason for new thread is to run timer, just schedule it on main run loop - see this post: http://stackoverflow.com/questions/2715844/cocoa-placing-an-nstimer-in-a-separate-thread – petert May 24 '11 at 10:52
  • This works. However i am scheduling timer on a separate thread because the timer fire interval is 0.001 seconds. On main thread it looks choppy. –  May 24 '11 at 11:10
  • 1
    Right. How about making your `NSTimer` instance variable a class variable (defined in your @interface section). When you invalidate it, set it to `nil` immediately afterwards. Then see if it works if you restart it? Curious. – petert May 24 '11 at 11:25
  • @petert, That works too!! I might want to invalidate my timer in some other method, so i had to do that. @Deepak, you mean updates in the timerFireMethod? –  May 24 '11 at 13:03
  • Ok, good to know. Quick search online confirms this approach - marking as an answer if you're happy. – petert May 24 '11 at 13:11

1 Answers1

0

Make your NSTimer instance variable a class variable. When you invalidate it, set it to nil immediately afterwards.

petert
  • 6,672
  • 3
  • 38
  • 46