How do I create a NSTimer on a background thread?

前端 未结 10 645
感情败类
感情败类 2020-11-28 02:04

I have a task that needs to be performed every 1 second. Currently I have an NSTimer firing repeatedly every 1 sec. How do I have the timer fire in a background thread (no

10条回答
  •  一向
    一向 (楼主)
    2020-11-28 02:47

    If you want your NSTimer to run in even background, do the following-

    1. call [self beginBackgroundTask] method in applicationWillResignActive methods
    2. call [self endBackgroundTask] method in applicationWillEnterForeground

    That's it

    -(void)beginBackgroundTask
    {
        bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [self endBackgroundTask];
        }];
    }
    
    -(void)endBackgroundTask
    {
        [[UIApplication sharedApplication] endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }
    

提交回复
热议问题