Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running NSTimer in NSOperationQueue thread

I'm trying to run an NSTimer on a thread set up by an NSOperationQueue

-(void)apiCallbackQueueManager:(NSString *)callid :(NSString *)service:(NSString *)action:(NSString *)data{

SEL theSelector = @selector(apiCallbackQueueTimer: service: action: data:);
NSMethodSignature * sig = [self methodSignatureForSelector:theSelector];
NSInvocation * theInvocation = [NSInvocation invocationWithMethodSignature:sig];
[theInvocation setTarget: self];
[theInvocation setSelector: theSelector];
[theInvocation setArgument: &callid atIndex: 2];
[theInvocation setArgument: &service atIndex: 3];
[theInvocation setArgument: &action atIndex: 4];
[theInvocation setArgument: &data atIndex: 5];

NSInvocationOperation* operation = [[NSInvocationOperation alloc] initWithInvocation:theInvocation];
NSOperationQueue *apiQueue = [[NSOperationQueue alloc] init];
[apiQueue addOperation:operation];
 }

-(void)apiCallbackQueueTimer:(NSString *)arg1 service:(NSString *)arg2 action:(NSString *)arg3 data:(NSString *)arg4{
apiTimer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(apiCallbackMonitor:) userInfo:[NSDictionary dictionaryWithObjectsAndKeys:arg1, @"callid", arg2, @"service", arg3, @"action", arg4, @"data", nil] repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:apiTimer forMode:NSDefaultRunLoopMode];
 }

-(void)apiCallbackMonitor:(NSTimer *)theTimer{
//do something
 }

Setting up the invocation and running the NSOperationQueue seem to be OK and the apiCallbackQueueTimer method gets called with the right arguments. The problem is that I cannot get the NSTimer to run and so get to my apiCallbackMonitor method.

I've read in the docs that NSTimer requires a run loop, so I've been trying to add one.

Can anyone see what I'm doing wrong?

like image 609
Phil John Avatar asked Jun 20 '26 14:06

Phil John


1 Answers

It turns out that I just needed to start the runloop.

Changing the last few lines of the apiCallbackQueueTimer solved the problem.

 NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:apiTimer forMode:NSRunLoopCommonModes];
[runLoop run];
like image 121
Phil John Avatar answered Jun 22 '26 03:06

Phil John



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!