Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way run repeated task while app is active

Tags:

ios

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.

like image 865
Sunway Logic Avatar asked Sep 18 '13 04:09

Sunway Logic


People also ask

How can you perform repeated tasks in a service?

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.


1 Answers

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

like image 162
kalyani puvvada Avatar answered Oct 16 '22 01:10

kalyani puvvada