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