Running a task in background thread periodically in iOS Running a task in background thread periodically in iOS multithreading multithreading

Running a task in background thread periodically in iOS


Scheduling the task using an NSTimer is indeed the right way to go. You just need to make sure you're running your heavy non-UI code on a background thread. Here's an example

- (void)viewDidLoad {    [super viewDidLoad];        [self startTimedTask];}- (void)startTimedTask{    NSTimer *fiveSecondTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(performBackgroundTask) userInfo:nil repeats:YES];}- (void)performBackgroundTask{    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        //Do background work        dispatch_async(dispatch_get_main_queue(), ^{            //Update UI        });    });}


dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){    //Background Thread    dispatch_async(dispatch_get_main_queue(), ^(void){        //Run UI Updates    });});

Try this