1# Deferred Task (ArkTS) 2<!--Kit: Background Tasks Kit--> 3<!--Subsystem: ResourceSchedule--> 4<!--Owner: @cheng-shichang--> 5<!--Designer: @zhouben25--> 6<!--Tester: @fenglili18--> 7<!--Adviser: @Brilliantry_Rui--> 8 9## Overview 10 11### Introduction 12 13If an application needs to execute a non-real-time task after switching to the background, for example, if the application wants to obtain emails irregularly when the network is available, the application can request deferred tasks. When the specified conditions (including the network type, charging type, storage status, battery status, and timing status) are met, the system adds the task to the execution queue. Then the system starts the application to execute the task based on the memory, power consumption, device temperature, and user habits. 14 15### Working Principle 16 17**Figure 1** Working principle of deferred task scheduling 18 19 20An application calls the **WorkScheduler** APIs to add, delete, and query deferred tasks. Based on the task-specific conditions (specified by **WorkInfo**, including the network type, charging type, and storage status) and system status (including the memory, power consumption, device temperature, and user habits), the WorkSchedulerService determines the time to schedule the tasks. 21 22When the scheduling conditions are met or the task scheduling ends, the system calls back **onWorkStart()** or **onWorkStop()** in [WorkSchedulerExtensionAbility](../reference/apis-backgroundtasks-kit/js-apis-WorkSchedulerExtensionAbility.md). The system also creates an independent process for the **WorkSchedulerExtensionAbility** and provides a duration for the **WorkSchedulerExtensionAbility** to run. You can implement your own service logic in the callback functions. 23 24 25### Constraints 26 27- **Quantity limit**: An application can request a maximum of 10 deferred tasks during a time segment. 28 29- **Execution frequency limit**: The system controls the execution frequency of deferred tasks <!--RP1-->based on the application activity group in the [device usage statistics](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-deviceUsageStatistics-sys.md)<!--RP1End-->. <!--Del-->Applications that request the WORK_SCHEDULER resource are placed in the efficiency resource exemption group.<!--DelEnd--> 30 31 **Table 1** Application activity groups 32 | Group| Deferred Task Execution Frequency| 33 | -------- | -------- | 34 | Group of active applications| At a minimum interval of 2 hours| 35 | Group of frequently used applications| At a minimum interval of 4 hours| 36 | Group of commonly used applications| At a minimum interval of 24 hours| 37 | Group of rarely used applications| At a minimum interval of 48 hours| 38 | Group of restricted applications| Forbidden| 39 | Group of applications never used| Forbidden|<!--Del--> 40 | Efficiency resource exemption group| No restriction|<!--DelEnd--> 41 42- **Timeout**: The WorkSchedulerExtensionAbility can run for a maximum of 2 minutes for a single callback. If the application does not cancel the deferred task upon a timeout, the system forcibly terminates the process for the WorkSchedulerExtensionAbility. <!--Del-->Privileged system applications can request the WORK_SCHEDULER resource to extend the duration to 20 minutes in the charging state and 10 minutes in the non-charging state.<!--DelEnd--> 43 44- **Scheduling delay**: The system schedules deferred tasks in a unified manner based on the memory, power consumption, device temperature, and user habits. For example, when the system memory resources are insufficient or the temperature reaches a certain level, the system delays task scheduling. 45 46- **Restrictions for WorkSchedulerExtensionAbility**: The following APIs cannot be called in the WorkSchedulerExtensionAbility: 47 48 [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-backgroundTaskManager.md) 49 50 [@ohos.backgroundTaskManager (Background Task Management)](../reference/apis-backgroundtasks-kit/js-apis-backgroundTaskManager.md) 51 52 [@ohos.multimedia.camera (Camera Management)](../reference/apis-camera-kit/arkts-apis-camera.md) 53 54 [@ohos.multimedia.audio (Audio Management)](../reference/apis-audio-kit/arkts-apis-audio.md) 55 56 [@ohos.multimedia.media (Media)](../reference/apis-media-kit/arkts-apis-media.md) 57 58 59## Available APIs 60 61**Table 2** Main APIs for deferred tasks 62 63The table below lists the APIs used for developing deferred tasks. For details about more APIs and their usage, see [@ohos.resourceschedule.workScheduler (Deferred Task Scheduling)](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md). 64| API| Description| 65| -------- | -------- | 66| startWork(work: WorkInfo): void; | Starts a deferred task.| 67| stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a deferred task.| 68| getWorkStatus(workId: number, callback: AsyncCallback<WorkInfo>): void; | Obtains the information about a deferred task. This API uses an asynchronous callback to return the result.| 69| getWorkStatus(workId: number): Promise<WorkInfo>; | Obtains the information about a deferred task. This API uses a promise to return the result.| 70| obtainAllWorks(callback: AsyncCallback\<Array\<WorkInfo>>): void; | Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.| 71| obtainAllWorks(): Promise<Array<WorkInfo>>; | Obtains all the deferred tasks. This API uses a promise to return the result.| 72| stopAndClearWorks(): void; | Stops and clears all the deferred tasks.| 73| isLastWorkTimeOut(workId: number, callback: AsyncCallback\<boolean>): void; | Checks whether the last execution of a deferred task has timed out. This API uses an asynchronous callback to return the result. It is applicable to repeated tasks.| 74| isLastWorkTimeOut(workId: number): Promise<boolean>; | Checks whether the last execution of a deferred task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks.| 75 76**Table 3** Options of WorkInfo 77| Name | Type | Mandatory | Description | 78| --------------- | --------------------------------- | ---- | ---------------- | 79| workId | number | Yes | ID of a deferred task. | 80| bundleName | string | Yes | Bundle name of the application where the deferred task is located. | 81| abilityName | string | Yes | Ability name in the bundle.| 82| networkType | [NetworkType](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md#networktype) | No | Network type. | 83| isCharging | boolean | No | Whether the device needs to enter the charging state to trigger deferred task scheduling.<br>- **true**: The device needs to enter the charging state to trigger deferred task scheduling.<br>- **false**: The device does not need to enter the charging state to trigger deferred task scheduling.| 84| chargerType | [ChargingType](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md#chargingtype) | No | Charging type. | 85| batteryLevel | number | No | Battery level. | 86| batteryStatus | [BatteryStatus](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md#batterystatus) | No | Battery status. | 87| storageRequest | [StorageRequest](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md#storagerequest) | No | Storage status. | 88| isRepeat | boolean | No | Whether the deferred task is repeated.<br>- **true**: The deferred task is repeated.<br>- **false**: The deferred task is not repeated.| 89| repeatCycleTime | number | No | Repeat interval, in milliseconds. | 90| repeatCount | number | No | Number of repeat times. | 91| isPersisted | boolean | No | Whether the registered deferred task can be saved in the system.<br>- **true**: The task can be saved. That is, the task can be restored after the system restarts.<br>- **false**: The task cannot be saved.| 92| isDeepIdle | boolean | No | Whether the device needs to enter the idle state to trigger deferred task scheduling.<br>- **true**: The device needs to enter the idle state to trigger deferred task scheduling.<br>- **false**: The device does not need to enter the idle state to trigger deferred task scheduling. | 93| idleWaitTime | number | No | Time to wait in the idle state before triggering deferred task scheduling, in milliseconds. | 94| parameters | [key: string]: number \| string \| boolean | No | Carried parameters.| 95 96The **WorkInfo** parameter is used to set conditions for triggering task scheduling. Its setting must comply with the following rules: 97 98- **workId**, **bundleName**, and **abilityName** are mandatory. **bundleName** must be set to the bundle name of the current application. 99 100- The carried parameters can be of the number, string, or boolean type. 101 102- At least one condition must be set, including the network type, charging type, storage status, battery status, and timing status. 103 104- For repeated tasks, **repeatCycleTime** must be at least 2 hours. When **isRepeat** is set, you must set **repeatCycleTime** or **repeatCount**. 105 106**Table 4** Deferred task scheduling callbacks 107 108The table below lists the APIs used for developing deferred task scheduling callbacks. For details about more APIs and their usage, see [@ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)](../reference/apis-backgroundtasks-kit/js-apis-WorkSchedulerExtensionAbility.md). 109| API| Description| 110| -------- | -------- | 111| onWorkStart(work: workScheduler.WorkInfo): void | Called when the system starts scheduling the deferred task.| 112| onWorkStop(work: workScheduler.WorkInfo): void | Called when the system stops scheduling the deferred task.| 113 114 115## How to Develop 116 117The development of deferred task scheduling consists of two steps: implementing the deferred task scheduling capability and implementing deferred task scheduling. 118 1191. **Implementing the deferred task scheduling capability**: Implement the callbacks for starting and stopping the WorkSchedulerExtensionAbility. 120 1212. **Implementing deferred task scheduling**: Call the **WorkScheduler** APIs to start and stop delayed tasks. 122 123### Implementing Deferred Task Scheduling Callbacks 124 1251. Create a project directory. 126 127 In the **./entry/src/main/ets** directory of the project, create a directory and an ArkTS file. For example, create a directory and name it **WorkSchedulerExtension**. In the **WorkSchedulerExtension** directory, create an ArkTS file named **WorkSchedulerExtension.ets** and implement the callbacks for deferred task scheduling. 128 1292. Import the module. 130 131 ```ts 132 import { WorkSchedulerExtensionAbility, workScheduler } from '@kit.BackgroundTasksKit'; 133 ``` 134 1353. Implement the lifecycle callbacks for the WorkSchedulerExtensionAbility. 136 137 ```ts 138 export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { 139 // Callback invoked when the system starts scheduling the deferred task. 140 onWorkStart(workInfo: workScheduler.WorkInfo) { 141 console.info(`onWorkStart, workInfo = ${JSON.stringify(workInfo)}`); 142 // Print the parameter, for example, key1, in parameters. 143 // console.info(`work info parameters: ${JSON.parse(workInfo.parameters?.toString()).key1}`) 144 } 145 146 // Callback invoked when the deferred task ends. This callback is triggered when the deferred task times out for 2 minutes or the stopWork API is called to cancel the task. 147 onWorkStop(workInfo: workScheduler.WorkInfo) { 148 console.info(`onWorkStop, workInfo is ${JSON.stringify(workInfo)}`); 149 } 150 } 151 ``` 152 1534. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) and set the tags as follows: 154 155 - Set **type** to **workScheduler**. 156 157 - Set **srcEntry** to the code path of the WorkSchedulerExtensionAbility component. 158 159 ```json 160 { 161 "module": { 162 "extensionAbilities": [ 163 { 164 "name": "MyWorkSchedulerExtensionAbility", 165 "srcEntry": "./ets/WorkSchedulerExtension/WorkSchedulerExtension.ets", 166 "type": "workScheduler" 167 } 168 ] 169 } 170 } 171 ``` 172 173 174### Implementing Deferred Task Scheduling 175 1761. Import the module. 177 178 ```ts 179 import { workScheduler } from '@kit.BackgroundTasksKit'; 180 import { BusinessError } from '@kit.BasicServicesKit'; 181 ``` 182 1832. Start a deferred task. 184 185 ```ts 186 // Create workinfo. 187 const workInfo: workScheduler.WorkInfo = { 188 workId: 1, 189 networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, 190 bundleName: 'com.example.application', 191 abilityName: 'MyWorkSchedulerExtensionAbility' 192 } 193 194 try { 195 workScheduler.startWork(workInfo); 196 console.info(`startWork success`); 197 } catch (error) { 198 console.error(`startWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 199 } 200 ``` 201 2023. Cancel the deferred task. 203 204 ```ts 205 // Create workinfo. 206 const workInfo: workScheduler.WorkInfo = { 207 workId: 1, 208 networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, 209 bundleName: 'com.example.application', 210 abilityName: 'MyWorkSchedulerExtensionAbility' 211 } 212 213 try { 214 workScheduler.stopWork(workInfo); 215 console.info(`stopWork success`); 216 } catch (error) { 217 console.error(`stopWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 218 } 219 ``` 220 221### Verifying Deferred Task Scheduling 222Check whether the **onWorkStart** and **onWorkStop** methods of WorkSchedulerExtensionAbility are correctly implemented and can be successfully called. 223 224 After the deferred task is requested, its callback can be triggered only when the required conditions are met. To quickly perform the verification, trigger the callback manually using the following [hidumper](../dfx/hidumper.md) command. 225 226 ```ts 227 $ hidumper -s 1904 -a '-t com.example.application MyWorkSchedulerExtensionAbility' 228 229 -------------------------------[ability]------------------------------- 230 231 232 ----------------------------------WorkSchedule---------------------------------- 233 ``` 234