1

I need a background operation to be scheduled every 10 minutes or so. The operation consists of gather objects from core data and uploading their information to a webservice not to change them in any way.

The approach I am thinking of is to create a nstimer inthe app delegate which fires every 10 minute. This will trigger a NSThread which will run the operation in the background not causing any disturbance for the user. The thread wil here after exit normally.

I have been looking into starting a thread and just set it to sleep after each time the operation is executed but the timer approach seemed to be the most clean.

Other suggestion on the web is to use runloops however I cannot see the use in this specific case.

Do anyone have a suggestion or want to tell how they tackle a similar situation.

Regards

Bjarke
  • 1,283
  • 11
  • 36

1 Answers1

2

The timer sounds like the right approach for actually starting your thread. To set that up just put this in your app delegate

[NSSTimer scheduledTimerWithTimeInterval:60.0 * 10.0 target:self selector:@selector(startBackgroundMethod) userInfo:nil repeats:YES];

Then create your background method code like this:

- (void)startBackgroundMethod
{
    //the timer calls this method runs on the main thread, so don't do any
    //significant work here. the call below kicks off the actual background thread
    [self performSelectorInBackground:@selector(backgroundMethod) withObject:nil];
}

- (void)backgroundMethod
{
    @autoreleasepool
    {
        //this runs in a  background thread, be careful not to do any UI updates
        //or interact with any methods that run on the main thread
        //without wrapping them with performSelectorOnMainThread:
    }
}

As for whether it's actually necessary to do this work in a background thread, that depends on what it is. Threads should be avoided unless strictly required due to the likelihood of concurrency bugs, so if you tell us what your thread is going to do we can advise on whether a runloop-based approach might be more suitable.

Nick Lockwood
  • 40,865
  • 11
  • 112
  • 103
  • Hi Nick, thank for the answer. Basically the thread has it owns shared context and retrieves objects from the persistent store. Then it takes information from the objects and uploads them to a web service. It do not change the objects in any way. And it is because of the scheduling and uploading that i am thinking of this approach. I am using ASIHTTPRequest for the uploading to the webservice. – Bjarke Jan 25 '12 at 13:34
  • You might want to rethink using ASI, since the developer has officially abandoned it and it doesn't work with ARC very well. You can do the upload using a regular asynchronous NSURLConnection, and that runs on the runloop without blocking the UI and without needing to spawn off a new thread (I assume it uses threads internally, but you don't need to manage concurrency yourself). – Nick Lockwood Jan 25 '12 at 14:18