0

Say you attach a timer to a runloop in a particular thread but the thread has exited before the timer gets triggered, causing the method to not be executed. Is this scenario possible?

Boon
  • 40,656
  • 60
  • 209
  • 315
  • 1
    @MarcusAdams A timer will fire on the next pass through the event loop if the requested time has elapsed. It'll never delay until next time through. – bbum Jul 26 '13 at 20:22
  • @bbum, I was thinking of repeating timers. Timer events can be skipped if they are too delayed. I deleted my comment. By "delayed call", we're probably not talking about repeating timers. :) – Marcus Adams Jul 26 '13 at 20:45
  • @MarcusAdams Ah.. OK. My misunderstanding. – bbum Jul 26 '13 at 20:50

3 Answers3

3

Certainly this is possible, and it's easy enough to demonstrate.

#import <Foundation/Foundation.h>

#define TIMER_INTERVAL 2.0

@interface Needle : NSObject

- (void)sew;
- (void)tick:(NSTimer *)tim;

@end

@implementation Needle
{
    NSTimer * tim;
}

- (void)sew
{
    @autoreleasepool{
        tim = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL
                                               target:self
                                             selector:@selector(tick:)
                                             userInfo:nil
                                              repeats:NO];

        while( ![[NSThread currentThread] isCancelled] ){
            [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
        }
    }
}

- (void)tick:(NSTimer *)timer
{
    NSLog(@"Let's get the bacon delivered!");
    [[NSThread currentThread] cancel];
}

@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        Needle * needle = [Needle new];
        NSThread * thread = [[NSThread alloc] initWithTarget:needle
                                                    selector:@selector(sew)
                                                      object:nil];

        [thread start];
        // Change this to "+ 1" to see the timer fire.
        NSTimeInterval interval = TIMER_INTERVAL - 1;
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:interval]];
        [thread cancel];

    }
    return 0;
}
jscs
  • 63,694
  • 13
  • 151
  • 195
0

Yes, unless you are on the main thread, there is no NSRunLoop keeping the thread alive and for the timers to attach to. You'll need to create one and let it run.

BergQuester
  • 6,167
  • 27
  • 39
0

Yes it is. This happens quite easily, if there is a timer but the app quits "prematurely". In this case, the timer's fire date will be lost - even when the app gets restarted before the timer's fire date that has been set formerly.

CouchDeveloper
  • 18,174
  • 3
  • 45
  • 67