BGTaskScheduler应用后台任务调度

1、在didFinishLaunchingWithOptions中创建任务,并设置任务标识(一段自己设置的字符串)

这个标识符需要跟info.plistBGTaskSchedulerPermittedIdentifiers所配置的数组中某个值保持一致。

info.plist配置
let queue = OperationQueue()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
 if BGTaskScheduler.shared.register(forTaskWithIdentifier: ProjectIdentifier, using: .global(), launchHandler: { task in
            
            task.expirationHandler = {
                LogPrint("expiration handler called of bg app refresh task")
            }
            
            self.handleAppRefresh(task: task as! BGAppRefreshTask)
            
        }) {
            LogPrint("successed to regist bgtask")
        }else {
            LogPrint("failed to regist bgtask")
        }
}


private func handleAppRefresh(task: BGTask) {
        
        /*
         LogPrint("bg app refresh task success called \(task.identifier)")
         
         task.expirationHandler = {
         LogPrint("expiration handler called of bg app refresh task")
         }
         
         task.setTaskCompleted(success: true)
         
         //后台执行时,继续提交一个request,方便下次调用。这样可以一直调用得到后台执行效果
         handleAppRefreshRequest()
         */
        
        task.expirationHandler = {[weak self] in
            LogPrint("expiration handler called of bg app refresh task")
            self?.queue.cancelAllOperations()
        }
        
        let operation = BlockOperation {
            LogPrint("bg app refresh task success called \(task.identifier)")
        }
        
        operation.completionBlock = {[weak self] in
            task.setTaskCompleted(success: operation.isCancelled)
            fflush(stdout)
            self?.handleAppRefreshRequest()
        }
        
        queue.addOperation(operation)
        
    }

func handleAppRefreshRequest() {
        
        let request = BGProcessingTaskRequest(identifier: ProjectIdentifier)
        request.requiresExternalPower = false
        request.requiresNetworkConnectivity = false
        request.earliestBeginDate = Date(timeIntervalSinceNow: BGTaskTimeInterval)
        
        
        LogPrint("request.date is \(request.earliestBeginDate!.toString())")
        
        do {
            try BGTaskScheduler.shared.submit(request)
        }catch let e {
            LogPrint("bgtask \(request.identifier)  sumit failed \(e.localizedDescription)")
        }
        
    }

后台任务执行效果如下:

2024-02-19 17:25:03.225 [AppDelegate:139] getBgtaskPermittedId() -> identifier is com.laisitech.backgroundtask.test
2024-02-19 17:25:03.226 [AppDelegate:28] application(_:didFinishLaunchingWithOptions:) -> successed to regist bgtask
2024-02-19 17:25:03.232 [SceneDelegate:16] scene(_:willConnectTo:options:) -> [n/a]
2024-02-19 17:25:03.243 [SceneDelegate:46] sceneWillEnterForeground(_:) -> [n/a]
2024-02-19 17:25:25.104 [AppDelegate:139] getBgtaskPermittedId() -> identifier is com.laisitech.backgroundtask.test
2024-02-19 17:25:25.105 [AppDelegate:28] application(_:didFinishLaunchingWithOptions:) -> successed to regist bgtask
2024-02-19 17:25:25.109 [SceneDelegate:16] scene(_:willConnectTo:options:) -> [n/a]
2024-02-19 17:25:25.118 [SceneDelegate:46] sceneWillEnterForeground(_:) -> [n/a]
2024-02-19 17:25:25.355 [SceneDelegate:32] sceneDidBecomeActive(_:) -> [n/a]
2024-02-19 17:25:28.194 [SceneDelegate:38] sceneWillResignActive(_:) -> [n/a]
2024-02-19 17:25:28.819 [SceneDelegate:54] sceneDidEnterBackground(_:) -> [n/a]
2024-02-19 17:25:28.821 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-19 17:40:28.820
2024-02-19 19:13:21.871 [SceneDelegate:46] sceneWillEnterForeground(_:) -> [n/a]
2024-02-19 19:13:22.168 [SceneDelegate:32] sceneDidBecomeActive(_:) -> [n/a]
2024-02-19 19:14:27.087 [SceneDelegate:38] sceneWillResignActive(_:) -> [n/a]
2024-02-19 19:14:27.698 [SceneDelegate:54] sceneDidEnterBackground(_:) -> [n/a]
2024-02-19 19:14:27.700 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-19 19:29:27.699
2024-02-19 20:42:13.495 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-19 20:42:13.500 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-19 20:57:13.498
2024-02-19 20:49:20.545 [SceneDelegate:46] sceneWillEnterForeground(_:) -> [n/a]
2024-02-19 20:49:20.855 [SceneDelegate:32] sceneDidBecomeActive(_:) -> [n/a]
2024-02-19 20:50:10.916 [SceneDelegate:38] sceneWillResignActive(_:) -> [n/a]
2024-02-19 20:50:11.514 [SceneDelegate:54] sceneDidEnterBackground(_:) -> [n/a]
2024-02-19 20:50:11.515 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-19 21:05:11.515
2024-02-19 21:22:41.068 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-19 21:22:41.070 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-19 21:37:41.070
2024-02-19 21:52:52.614 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-19 21:52:52.615 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-19 22:07:52.615
2024-02-19 22:22:55.236 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-19 22:22:55.238 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-19 22:37:55.238
2024-02-19 22:52:57.239 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-19 22:52:57.243 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-19 23:07:57.241
2024-02-19 23:23:03.577 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-19 23:23:03.580 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-19 23:38:03.579
2024-02-19 23:53:09.425 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-19 23:53:09.427 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 00:08:09.426
2024-02-20 00:23:09.594 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 00:23:09.596 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 00:38:09.595
2024-02-20 00:53:15.152 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 00:53:15.154 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 01:08:15.153
2024-02-20 01:23:15.582 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 01:23:15.585 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 01:38:15.584
2024-02-20 01:53:18.587 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 01:53:18.590 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 02:08:18.589
2024-02-20 02:23:24.272 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 02:23:24.275 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 02:38:24.274
2024-02-20 02:53:24.861 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 02:53:24.863 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 03:08:24.863
2024-02-20 03:23:33.577 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 03:23:33.581 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 03:38:33.580
2024-02-20 03:53:39.027 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 03:53:39.030 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 04:08:39.029
2024-02-20 04:23:40.881 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 04:23:40.883 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 04:38:40.882
2024-02-20 04:53:44.685 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 04:53:44.688 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 05:08:44.686
2024-02-20 05:23:46.503 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 05:23:46.506 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 05:38:46.505
2024-02-20 05:54:02.456 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 05:54:02.459 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 06:09:02.457
2024-02-20 06:24:39.210 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 06:24:39.213 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 06:39:39.211
2024-02-20 06:54:50.785 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 06:54:50.786 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 07:09:50.786
2024-02-20 07:24:52.157 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 07:24:52.159 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 07:39:52.158
2024-02-20 07:54:57.264 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 07:54:57.265 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 08:09:57.265
2024-02-20 08:25:09.176 [AppDelegate:72] handleAppRefresh(task:) -> bg app refresh task success called com.laisitech.backgroundtask.test
2024-02-20 08:25:09.180 [AppDelegate:93] handleAppRefreshRequest() -> request.date is 2024-02-20 08:40:09.179
2024-02-20 08:31:39.826 [SceneDelegate:46] sceneWillEnterForeground(_:) -> [n/a]
2、BGAppRefreshTaskRequest提交任务注意事项
  • request的Identifier必须BGTaskScheduler.shared.register时使用的identifier是同一个值
  • refreshtaskrequest主要用在网络拉取数据,所以如果注册的任务在 launchHandler不是网络数据拉取的话一般不执行。
    不熟悉的情况下使用这个request测试,在后台到期基本不会触发任务。
3、BGProcessingTaskRequest提交任务注意事项
  • request的Identifier必须BGTaskScheduler.shared.register时使用的identifier是同一个值
  • ProcessingTaskRequest是广泛的任务处理。
    有是否需要连接网络才能触发任务的属性requiresNetworkConnectivity,默认false。
    也有是否需要连接电源才能触发任务的属性requiresExternalPower,默认false。
4、仅测试后台任务执行情况

如果仅仅是测试BGTaskScheduler注册的任务后台执行情况,建议使用BGProcessingTaskRequest,这个不会强制需要网络条件。
经过一天一夜的测试:
手机充电时,BGProcessingTaskRequest设置earliestBeginDate15分钟时,APP在后台大概半小时执行一次后台任务。未充电的情况下未测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值