Is it possible to call my function in the background after certain interval programmatically in iPhone SDK development? I want to call one particular function in the backgro
To call the function on the main thread, use an NSTimer.
To call it on another thread, create an NSOperation and set up an NSOperationQueue to call it.
You can have a timer, look into NSTimer for that that will fire off every 10 minutes, in order to make i t happen i n the background you have a few options ill name two. First of note that any UI work should not be done in another thread since UIKit is not thread safe.
You can subclass NSThread and use it to do you process in the background
You can use NSObjects performSelectorInBackground method which basically creates a thread and executes the method. Heres a reference http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorInBackground:withObject:
NSThread reference here http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html
NSTimer reference here http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html
Easiest way is to schedule a NSTimer
on the main threads run-loop. I suggest that the following code is implemented on your application delegate, and that you call setupTimer
from applicationDidFinishLaunching:
.
-(void)setupTimer;
{
NSTimer* timer = [NSTimer timerWithTimeInterval:10 * 60
target:self
selector:@selector(triggerTimer:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void)triggerTimer:(NSTimer*)timer;
{
// Do your stuff
}
If your stuff here takes a long time, and you can not hold up the main thread then either call your stuff using:
[self performSelectorInBackground:@selector(myStuff) withObject:nil];
Or you could run the NSTimer
on a background thread by with something like this (I am intentionally leaking the thread object):
-(void)startTimerThread;
{
NSThread* thread = [[NSThread alloc] initWithTarget:self
selector:@selector(setupTimerThread)
withObject:nil];
[thread start];
}
-(void)setupTimerThread;
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSTimer* timer = [NSTimer timerWithTimeInterval:10 * 60
target:self
selector:@selector(triggerTimer:)
userInfo:nil
repeats:YES];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forModes:NSRunLoopCommonModes];
[runLoop run];
[pool release];
}
-(void)triggerTimer:(NSTimer*)timer;
{
// Do your stuff
}