I want to run a task in the background while app is active and running. The task should be executed repeatedly in every 2 minutes or so. If the application is inactive then the 'background repeated task' should be paused and it should continue if the app is active again. What is the best way to do this ? Please help.
There are at least four ways to run periodic tasks: Handler - Execute a Runnable task on the UIThread after an optional delay. ScheduledThreadPoolExecutor - Execute periodic tasks with a background thread pool. AlarmManager - Execute any periodic task in the background as a service.
You can try like this.. Write the following line at where do you want to call the timer..
NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(timerFired:)
userInfo:nil
repeats:YES];
[aTimer fire];
-(void)timerFired:(NSTimer *) theTimer
{
//Do you your work here..
}
You can also stop the timer with [aTimer invalidate]; aTimer=nil;
this code.
And also you can check this link https://stackoverflow.com/questions/11058571/nstimer-timerwithtimeinterval
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With