1# Deferred Task (ArkTS) 2 3## Overview 4 5### Introduction 6 7If 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. 8 9### Working Principle 10 11**Figure 1** Working principle of deferred task scheduling 12 13 14 15An 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. 16 17When 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. 18 19 20### Constraints 21 22- **Quantity limit**: An application can request a maximum of 10 deferred tasks during a time segment. 23 24- **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--> 25 26 **Table 1** Application activity groups 27 | Group| Deferred Task Execution Frequency| 28 | -------- | -------- | 29 | Group of active applications| At a minimum interval of 2 hours| 30 | Group of frequently used applications| At a minimum interval of 4 hours| 31 | Group of applications that are used neither frequently nor rarely| At a minimum interval of 24 hours| 32 | Group of rarely used applications| At a minimum interval of 48 hours| 33 | Group of restricted applications| Forbidden| 34 | Group of applications never used| Forbidden|<!--Del--> 35 | Efficiency resource exemption group| No restriction|<!--DelEnd--> 36 37- **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--> 38 39- **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. 40 41- **Restrictions for WorkSchedulerExtensionAbility**: The following APIs cannot be called in the WorkSchedulerExtensionAbility: 42 43 [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-backgroundTaskManager.md) 44 45 [@ohos.backgroundTaskManager (Background Task Management)](../reference/apis-backgroundtasks-kit/js-apis-backgroundTaskManager.md) 46 47 [@ohos.multimedia.camera (Camera Management)](../reference/apis-camera-kit/js-apis-camera.md) 48 49 [@ohos.multimedia.audio (Audio Management)](../reference/apis-audio-kit/js-apis-audio.md) 50 51 [@ohos.multimedia.media (Media)](../reference/apis-media-kit/js-apis-media.md) 52 53 54## Available APIs 55 56The 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). 57 58**Table 2** Main APIs for deferred tasks 59 60| API| Description| 61| -------- | -------- | 62| startWork(work: WorkInfo): void; | Starts a deferred task.| 63| stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a deferred task.| 64| getWorkStatus(workId: number, callback: AsyncCallback<WorkInfo>): void; | Obtains the information about a deferred task. This API uses an asynchronous callback to return the result.| 65| getWorkStatus(workId: number): Promise<WorkInfo>; | Obtains the information about a deferred task. This API uses a promise to return the result.| 66| obtainAllWorks(callback: AsyncCallback\<Array\<WorkInfo>>): void; | Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.| 67| obtainAllWorks(): Promise<Array<WorkInfo>>; | Obtains all the deferred tasks. This API uses a promise to return the result.| 68| stopAndClearWorks(): void; | Stops and clears all the deferred tasks.| 69| 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.| 70| 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.| 71 72**Table 3** Options of WorkInfo 73| Name | Type | Mandatory | Description | 74| --------------- | --------------------------------- | ---- | ---------------- | 75| workId | number | Yes | ID of a deferred task. | 76| bundleName | string | Yes | Bundle name of the application where the deferred task is located. | 77| abilityName | string | Yes | Ability name in the bundle.| 78| networkType | [NetworkType](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md#networktype) | No | Network type. | 79| isCharging | boolean | No | Whether the device needs to enter the charging state to trigger deferred task scheduling.<br>The value **true** means that the device needs to enter the charging state to trigger deferred task scheduling, and **false** means the opposite.| 80| chargerType | [ChargingType](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md#chargingtype) | No | Charging type. | 81| batteryLevel | number | No | Battery level. | 82| batteryStatus | [BatteryStatus](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md#batterystatus) | No | Battery status. | 83| storageRequest | [StorageRequest](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md#storagerequest) | No | Storage status. | 84| isRepeat | boolean | No | Whether the deferred task is repeated.<br>The value **true** means that the task is repeated, and **false** means the opposite.| 85| repeatCycleTime | number | No | Repeat interval, in milliseconds. | 86| repeatCount | number | No | Number of repeat times. | 87| isPersisted | boolean | No | Whether the registered deferred task can be saved in the system.<br>The value **true** means that the task can be saved. That is, the task can be restored after the system restarts. The value **false** means the opposite.| 88| isDeepIdle | boolean | No | Whether the device needs to enter the idle state to trigger deferred task scheduling.<br>The value **true** means that the device needs to enter the idle state to trigger deferred task scheduling, and **false** means the opposite. | 89| idleWaitTime | number | No | Time to wait in the idle state before triggering deferred task scheduling, in milliseconds. | 90| parameters | [key: string]: number \| string \| boolean | No | Carried parameters.| 91 92The **WorkInfo** parameter is used to set conditions for triggering task scheduling. Its setting must comply with the following rules: 93 94- **workId**, **bundleName**, and **abilityName** are mandatory. **bundleName** must be set to the bundle name of the current application. 95 96- The carried parameters can be of the number, string, or boolean type. 97 98- At least one condition must be set, including the network type, charging type, storage status, battery status, and timing status. 99 100- For repeated tasks, **repeatCycleTime** must be at least 2 hours. When **isRepeat** is set, you must set **repeatCycleTime** or **repeatCount**. 101 102The 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). 103 104**Table 4** Deferred task scheduling callbacks 105 106| API| Description| 107| -------- | -------- | 108| onWorkStart(work: workScheduler.WorkInfo): void | Called when the system starts scheduling the deferred task.| 109| onWorkStop(work: workScheduler.WorkInfo): void | Called when the system stops scheduling the deferred task.| 110 111 112## How to Develop 113 114The development of deferred task scheduling consists of two steps: implementing the deferred task scheduling capability and implementing deferred task scheduling. 115 1161. **Implementing the deferred task scheduling capability**: Implement the callbacks for starting and stopping the WorkSchedulerExtensionAbility. 117 1182. **Implementing deferred task scheduling**: Call the **WorkScheduler** APIs to start and stop delayed tasks. 119 120### Implementing Deferred Task Scheduling Callbacks 121 1221. Create a project directory. 123 124 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. 125 1262. Import the module. 127 128 ```ts 129 import { WorkSchedulerExtensionAbility, workScheduler } from '@kit.BackgroundTasksKit'; 130 ``` 131 1323. Implement the lifecycle callbacks for the WorkSchedulerExtensionAbility. 133 134 ```ts 135 export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { 136 // Callback invoked when the system starts scheduling the deferred task. 137 onWorkStart(workInfo: workScheduler.WorkInfo) { 138 console.info(`onWorkStart, workInfo = ${JSON.stringify(workInfo)}`); 139 // Print the parameter, for example, key1, in parameters. 140 // console.info(`work info parameters: ${JSON.parse(workInfo.parameters?.toString()).key1}`) 141 } 142 143 // Callback invoked when the system stops scheduling the deferred task. 144 onWorkStop(workInfo: workScheduler.WorkInfo) { 145 console.info(`onWorkStop, workInfo is ${JSON.stringify(workInfo)}`); 146 } 147 } 148 ``` 149 1504. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) and set the tags as follows: 151 152 - Set **type** to **workScheduler**. 153 154 - Set **srcEntry** to the code path of the WorkSchedulerExtensionAbility component. 155 156 ```json 157 { 158 "module": { 159 "extensionAbilities": [ 160 { 161 "name": "MyWorkSchedulerExtensionAbility", 162 "srcEntry": "./ets/WorkSchedulerExtension/WorkSchedulerExtension.ets", 163 "type": "workScheduler" 164 } 165 ] 166 } 167 } 168 ``` 169 170 171### Implementing Deferred Task Scheduling 172 1731. Import the module. 174 175 ```ts 176 import { workScheduler } from '@kit.BackgroundTasksKit'; 177 import { BusinessError } from '@kit.BasicServicesKit'; 178 ``` 179 1802. Start a deferred task. 181 182 ```ts 183 // Create workinfo. 184 const workInfo: workScheduler.WorkInfo = { 185 workId: 1, 186 networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, 187 bundleName: 'com.example.application', 188 abilityName: 'MyWorkSchedulerExtensionAbility' 189 } 190 191 try { 192 workScheduler.startWork(workInfo); 193 console.info(`startWork success`); 194 } catch (error) { 195 console.error(`startWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 196 } 197 ``` 198 1993. Cancel the deferred task. 200 201 ```ts 202 // Create workinfo. 203 const workInfo: workScheduler.WorkInfo = { 204 workId: 1, 205 networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, 206 bundleName: 'com.example.application', 207 abilityName: 'MyWorkSchedulerExtensionAbility' 208 } 209 210 try { 211 workScheduler.stopWork(workInfo); 212 console.info(`stopWork success`); 213 } catch (error) { 214 console.error(`stopWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 215 } 216 ``` 217 218