• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Deferred Task
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![WorkScheduler](figures/WorkScheduler.png)
14
15An application calls the **WorkScheduler** APIs to register, 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/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 based on the [application activity group](../reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md). Applications that request the WORK_SCHEDULER resource are placed in the efficiency resource exemption group.
25
26  **Table 1** Application activity groups
27
28  | Group| Deferred Task Execution Frequency|
29  | -------- | -------- |
30  | Group of active applications| At a minimum interval of 2 hours|
31  | Group of frequently used applications| At a minimum interval of 4 hours|
32  | Group of applications that are used neither frequently nor rarely| At a minimum interval of 24 hours|
33  | Group of rarely used applications| At a minimum interval of 48 hours|
34  | Group of restricted applications| Forbidden|
35  | Group of applications never used| Forbidden|
36  | Efficiency resource exemption group| No restriction|
37
38- **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. 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.
39
40- **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.
41
42- **Restrictions for WorkSchedulerExtensionAbility**: The following APIs cannot be called in the WorkSchedulerExtensionAbility:
43
44  [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md)
45
46  [@ohos.backgroundTaskManager (Background Task Management)](../reference/apis/js-apis-backgroundTaskManager.md)
47
48  [@ohos.multimedia.camera (Camera Management)](../reference/apis/js-apis-camera.md)
49
50  [@ohos.multimedia.audio (Audio Management)](../reference/apis/js-apis-audio.md)
51
52  [@ohos.multimedia.media (Media)](../reference/apis/js-apis-media.md)
53
54
55## Available APIs
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/js-apis-resourceschedule-workScheduler.md).
58
59**Table 2** Main APIs for deferred tasks
60
61| API| Description|
62| -------- | -------- |
63| startWork(work: WorkInfo): void; | Starts a deferred task.|
64| stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a deferred task.|
65| getWorkStatus(workId: number, callback: AsyncCallback<WorkInfo>): void; | Obtains the information about a deferred task. This API uses an asynchronous callback to return the result.|
66| getWorkStatus(workId: number): Promise<WorkInfo>; | Obtains the information about a deferred task. This API uses a promise to return the result.|
67| obtainAllWorks(callback: AsyncCallback<void>): Array<WorkInfo>; | Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.|
68| obtainAllWorks(): Promise<Array<WorkInfo>>; | Obtains all the deferred tasks. This API uses a promise to return the result.|
69| stopAndClearWorks(): void; | Stops and clears all the deferred tasks.|
70| isLastWorkTimeOut(workId: number, callback: AsyncCallback<void>): boolean; | 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.|
71| 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.|
72
73**Table 3** Options of WorkInfo
74| Name            | Type                               | Mandatory  | Description              |
75| --------------- | --------------------------------- | ---- | ---------------- |
76| workId          | number                            | Yes   | ID of a deferred task.         |
77| bundleName      | string                            | Yes   | Bundle name of the application that requests the deferred task.          |
78| abilityName     | string                            | Yes   | Name of the ability to be notified by a deferred task scheduling callback.|
79| networkType     | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype)       | No   | Network type.            |
80| 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.|
81| chargerType     | [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype)     | No   | Charging type.            |
82| batteryLevel    | number                            | No   | Battery level.             |
83| batteryStatus   | [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus)   | No   | Battery status.            |
84| storageRequest  | [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) | No   | Storage status.            |
85| isRepeat        | boolean                           | No   | Whether the deferred task is repeated.<br>The value** true** means that the task is repeated, and **false** means the opposite.|
86| repeatCycleTime | number                            | No   | Repeat interval, in milliseconds.            |
87| repeatCount     | number                            | No   | Number of repeat times.            |
88| 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.|
89| 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.  |
90| idleWaitTime    | number                            | No   | Time to wait in the idle state before triggering deferred task scheduling, in milliseconds.          |
91| parameters      | [key: string]: number \| string \| boolean  | No   | Carried parameters.|
92
93The **WorkInfo** parameter is used to set conditions for triggering task scheduling. Its setting must comply with the following rules:
94
95- **workId**, **bundleName**, and **abilityName** are mandatory. **bundleName** must be set to the bundle name of the current application.
96
97- The carried parameters can be of the number, string, or boolean type.
98
99- At least one condition must be set, including the network type, charging type, storage status, battery status, and timing status.
100
101- For repeated tasks, **repeatCycleTime** must be at least 20 minutes. When **isRepeat** is set, you must set **repeatCycleTime** or **repeatCount**.
102
103The 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/js-apis-WorkSchedulerExtensionAbility.md).
104
105**Table 4** Deferred task scheduling callbacks
106
107| API| Description|
108| -------- | -------- |
109| onWorkStart(work: workScheduler.WorkInfo): void | Called when the system starts scheduling the deferred task.|
110| onWorkStop(work: workScheduler.WorkInfo): void | Called when the system stops scheduling the deferred task.|
111
112
113## How to Develop
114
115The development of deferred task scheduling consists of two steps: implementing the deferred task scheduling capability and implementing deferred task scheduling.
116
1171. **Implementing the deferred task scheduling capability**: Implement the callbacks for starting and stopping the WorkSchedulerExtensionAbility.
118
1192. **Implementing deferred task scheduling**: Call the **WorkScheduler** APIs to start and stop delayed tasks.
120
121### Implementing Deferred Task Scheduling Callbacks
122
1231. Create a project directory.
124
125   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 **extension**. In the **extension** directory, create an ArkTS file named **WorkSchedulerExtension.ets** and implement the callbacks for deferred task scheduling.
126
1272. Import the module.
128
129   ```ts
130   import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
131   import workScheduler from '@ohos.resourceschedule.workScheduler';
132   ```
133
1343. Implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
135
136   ```ts
137   export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
138     // Callback invoked when the system starts scheduling the deferred task.
139     onWorkStart(workInfo: workScheduler.WorkInfo) {
140       console.info(`onWorkStart, workInfo = ${JSON.stringify(workInfo)}`);
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             "label": "$string:WorkSchedulerExtensionAbility_label",
164             "description": "$string:WorkSchedulerExtensionAbility_desc",
165             "type": "workScheduler"
166           }
167         ]
168     }
169   }
170   ```
171
172
173### Implementing Deferred Task Scheduling
174
1751. Import the module.
176
177   ```ts
178   import workScheduler from '@ohos.resourceschedule.workScheduler';
179   import { BusinessError } from '@ohos.base';
180   ```
181
1822. Start a deferred task.
183
184   ```ts
185   const workInfo: workScheduler.WorkInfo = {
186     workId: 1,
187     networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
188     bundleName: 'com.example.application',
189     abilityName: 'MyWorkSchedulerExtensionAbility'
190   }
191
192   try {
193     workScheduler.startWork(workInfo);
194     console.info(`startWork success`);
195   } catch (error) {
196     console.error(`startWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
197   }
198   ```
199
2003. Cancel the deferred task.
201
202   ```ts
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