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