Regan
Regan

Reputation: 1497

NSTimer and NSInvocation, timer does not fire

First I create an NSInvocation, because the method I want to call with the timer has several parameters, which I set here

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(addStockPriceForArticle:forInterval:)]];
[invocation setArgument:&varArticle atIndex:2];
NSNumber *interval = [NSNumber numberWithInt:60];
[invocation setArgument:&interval atIndex:3];

The documentation says to start at index 2 when setting the arguments, because indices 0 and 1 are the target and selector.

Then I figure out the interval I want the timer to be. In this case, I am calling the timer 60 minutes after an article is published, so the interval is 60 - timeSincePubDate in minutes, which I multiply by 60 to be the interval in seconds for the timer.

int timeUntilCheck = (60-timeSincePubDate)*60;

Then I create the timer with the interval and add it to the run loop. I've never done this before, but it seems straightforward enough; I'm not sure why it doesn't ever call the method it is supposed to.

[[NSRunLoop currentRunLoop] addTimer:[NSTimer timerWithTimeInterval:timeUntilCheck invocation:invocation repeats:NO]
                                     forMode:NSDefaultRunLoopMode];

Upvotes: 1

Views: 619

Answers (1)

jscs
jscs

Reputation: 64022

You need to add the timer to a run loop that a) exists and b) is running, or it will never fire, and you probably want your callback to happen on the main thread anyways.

Add the timer to the main thread's run loop like this:

[[NSRunLoop mainRunLoop] addTimer:[NSTimer timerWithTimeInterval:timeUntilCheck invocation:invocation repeats:NO]
                             forMode:NSDefaultRunLoopMode];

Upvotes: 1

Related Questions