• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Work Scheduler
2
3The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints.
4
5The system executes Work Scheduler tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.
6
7>  **NOTE**
8>
9>  The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
10
11
12## Modules to Import
13
14```
15import workScheduler from '@ohos.workScheduler'
16```
17
18## workScheduler.startWork
19startWork(work: WorkInfo): boolean
20
21Instructs the **WorkSchedulerService** to add the specified task to the execution queue.
22
23**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
24
25**Parameters**
26
27| Name | Type                   | Mandatory  | Description            |
28| ---- | --------------------- | ---- | -------------- |
29| work | [WorkInfo](#workinfo) | Yes   | Task to be added to the execution queue.|
30
31**Return value**
32
33| Type     | Description                              |
34| ------- | -------------------------------- |
35| boolean | Returns **true** if the task is added to the execution queue; returns **false** otherwise.|
36
37**Example**
38
39```
40  let workInfo = {
41      workId: 1,
42      batteryLevel:50,
43      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
44      isRepeat: false,
45      isPersisted: true,
46      bundleName: "com.example.myapplication",
47      abilityName: "MyExtension"
48  }
49  var res = workScheduler.startWork(workInfo);
50  console.info("workschedulerLog res:" + res);
51```
52
53## workScheduler.stopWork
54stopWork(work: WorkInfo, needCancel?: boolean): boolean
55
56Instructs the **WorkSchedulerService** to stop the specified task.
57
58**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
59
60**Parameters**
61
62| Name       | Type                   | Mandatory  | Description        |
63| ---------- | --------------------- | ---- | ---------- |
64| work       | [WorkInfo](#workinfo) | Yes   | Task to stop. |
65| needCancel | boolean               | Yes   | Whether to cancel the task.|
66
67**Return value**
68
69| Type     | Description                     |
70| ------- | ----------------------- |
71| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
72
73**Example**
74
75```
76  let workInfo = {
77      workId: 1,
78      batteryLevel:50,
79      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
80      isRepeat: false,
81      isPersisted: true,
82      bundleName: "com.example.myapplication",
83      abilityName: "MyExtension"
84     }
85  var res = workScheduler.stopWork(workInfo, false);
86  console.info("workschedulerLog res:" + res);
87```
88
89## workScheduler.getWorkStatus
90getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void
91
92Obtains the latest task status. This API uses an asynchronous callback to return the result.
93
94**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
95
96**Parameters**
97
98| Name     | Type                                   | Mandatory  | Description                                      |
99| -------- | ------------------------------------- | ---- | ---------------------------------------- |
100| workId   | number                                | Yes   | Task ID.                                |
101| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes   | Callback used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.|
102
103**Example**
104
105```
106  workScheduler.getWorkStatus(50, (err, res) => {
107    if (err) {
108      console.info('workschedulerLog getWorkStatus failed, because:' + err.data);
109    } else {
110      for (let item in res) {
111        console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
112      }
113    }
114  });
115```
116
117## workScheduler.getWorkStatus
118getWorkStatus(workId: number): Promise\<WorkInfo>
119
120Obtains the latest task status. This API uses a promise to return the result.
121
122**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
123
124**Parameters**
125
126| Name   | Type    | Mandatory  | Description      |
127| ------ | ------ | ---- | -------- |
128| workId | number | Yes   | Task ID.|
129
130**Return value**
131
132| Type                             | Description                                      |
133| ------------------------------- | ---------------------------------------- |
134| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.|
135
136**Example**
137
138```
139  workScheduler.getWorkStatus(50).then((res) => {
140    for (let item in res) {
141      console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
142    }
143  }).catch((err) => {
144    console.info('workschedulerLog getWorkStatus failed, because:' + err.data);
145  })
146```
147
148## workScheduler.obtainAllWorks
149obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>
150
151Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result.
152
153**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
154
155**Parameters**
156
157| Name     | Type                  | Mandatory  | Description                             |
158| -------- | -------------------- | ---- | ------------------------------- |
159| callback | AsyncCallback\<void> | Yes   | Callback used to return all tasks associated with the current application. |
160
161**Return value**
162
163| Type                           | Description             |
164| ----------------------------- | --------------- |
165| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.|
166
167**Example**
168
169```
170  workScheduler.obtainAllWorks((err, res) =>{
171    if (err) {
172      console.info('workschedulerLog obtainAllWorks failed, because:' + err.data);
173    } else {
174      console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
175    }
176  });
177```
178
179## workScheduler.obtainAllWorks
180obtainAllWorks(): Promise<Array\<WorkInfo>>
181
182Obtains all tasks associated with this application. This API uses a promise to return the result.
183
184**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
185
186**Return value**
187
188| Type                                    | Description                            |
189| -------------------------------------- | ------------------------------ |
190| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return all tasks associated with the current application. |
191
192**Example**
193
194```
195  workScheduler.obtainAllWorks().then((res) => {
196    console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
197  }).catch((err) => {
198    console.info('workschedulerLog obtainAllWorks failed, because:' + err.data);
199  })
200```
201
202## workScheduler.stopAndClearWorks
203stopAndClearWorks(): boolean
204
205Stops and cancels all tasks associated with the current application.
206
207**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
208
209**Example**
210
211```
212  let res = workScheduler.stopAndClearWorks();
213  console.info("workschedulerLog res:" + res);
214```
215
216## workScheduler.isLastWorkTimeOut
217isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
218
219Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result.
220
221**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
222
223**Parameters**
224
225| Name     | Type                  | Mandatory  | Description                                      |
226| -------- | -------------------- | ---- | ---------------------------------------- |
227| workId   | number               | Yes   | Task ID.                                |
228| callback | AsyncCallback\<void> | Yes   | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
229
230**Return value**
231
232| Type     | Description                                      |
233| ------- | ---------------------------------------- |
234| boolean | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
235
236**Example**
237
238```
239  workScheduler.isLastWorkTimeOut(500, (err, res) =>{
240    if (err) {
241      console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.data);
242    } else {
243      console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
244    }
245  });
246```
247
248## workScheduler.isLastWorkTimeOut
249isLastWorkTimeOut(workId: number): Promise\<boolean>
250
251Checks whether the last execution of the specified task timed out. This API uses a promise to return the result.
252
253**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
254
255**Parameters**
256
257| Name   | Type    | Mandatory  | Description      |
258| ------ | ------ | ---- | -------- |
259| workId | number | Yes   | Task ID.|
260
261**Return value**
262
263| Type               | Description                                      |
264| ----------------- | ---------------------------------------- |
265| Promise\<boolean> | Promise used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
266
267**Example**
268
269```
270  workScheduler.isLastWorkTimeOut(500)
271    .then(res => {
272      console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
273    })
274    .catch(err =>  {
275      console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.data);
276    });
277```
278
279## WorkInfo
280Provides detailed information about the task. For details about the constraints on configuring **WorkInfo**, see [Work Scheduler Overview](../../task-management/work-scheduler-overview.md).
281
282**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
283
284| Name            | Type                               | Mandatory  | Description              |
285| --------------- | --------------------------------- | ---- | ---------------- |
286| workId          | number                            | Yes   | Task ID.         |
287| bundleName      | string                            | Yes   | Name of the Work Scheduler task bundle.          |
288| abilityName     | string                            | Yes   | Name of the component to be notified by a Work Scheduler callback.|
289| networkType     | [NetworkType](#networktype)       | No   | Network type.            |
290| isCharging      | boolean                           | No   | Whether the device is charging.            |
291| chargerType     | [ChargingType](#chargingtype)     | No   | Charging type.            |
292| batteryLevel    | number                            | No   | Battery level.              |
293| batteryStatus   | [BatteryStatus](#batterystatus)   | No   | Battery status.            |
294| storageRequest  | [StorageRequest](#storagerequest) | No   | Storage status.            |
295| isRepeat        | boolean                           | No   | Whether the task is repeated.          |
296| repeatCycleTime | number                            | No   | Repeat interval.            |
297| repeatCount     | number                            | No   | Number of repeat times.            |
298| isPersisted     | boolean                           | No   | Whether to enable persistent storage for the task.       |
299
300## NetworkType
301Enumerates the network types that can trigger the task.
302
303**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
304
305| Name                    | Default Value | Description                     |
306| ---------------------- | ---- | ----------------------- |
307| NETWORK_TYPE_ANY       | 0    | Any network type.    |
308| NETWORK_TYPE_MOBILE    | 1    | Mobile network.   |
309| NETWORK_TYPE_WIFI      | 2    | Wi-Fi network.  |
310| NETWORK_TYPE_BLUETOOTH | 3    | Bluetooth network.|
311| NETWORK_TYPE_WIFI_P2P  | 4    | Wi-Fi P2P network. |
312| NETWORK_TYPE_ETHERNET  | 5    | Ethernet.       |
313
314## ChargingType
315Enumerates the charging types that can trigger the task.
316
317**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
318
319| Name                       | Default Value | Description                  |
320| ------------------------- | ---- | -------------------- |
321| CHARGING_PLUGGED_ANY      | 0    | Any charging type.|
322| CHARGING_PLUGGED_AC       | 1    | DC charging.   |
323| CHARGING_PLUGGED_USB      | 2    | USB charging.    |
324| CHARGING_PLUGGED_WIRELESS | 3    | Wireless charging.   |
325
326## BatteryStatus
327Enumerates the battery states that can trigger the task.
328
329**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
330
331| Name                        | Default Value | Description                        |
332| -------------------------- | ---- | -------------------------- |
333| BATTERY_STATUS_LOW         | 0    | A low battery alert is displayed.            |
334| BATTERY_STATUS_OKAY        | 1    | The battery level is restored from low to normal.      |
335| BATTERY_STATUS_LOW_OR_OKAY | 2    | The battery level is restored from low to normal, or a low battery alert is displayed.|
336
337## StorageRequest
338Enumerates the storage states that can trigger the task.
339
340**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
341
342| Name                       | Default Value | Description                            |
343| ------------------------- | ---- | ------------------------------ |
344| STORAGE_LEVEL_LOW         | 0    | The storage space is insufficient.              |
345| STORAGE_LEVEL_OKAY        | 1    | The storage space is restored from insufficient to normal.        |
346| STORAGE_LEVEL_LOW_OR_OKAY | 2    | The storage space is restored from insufficient to normal, or the storage space is insufficient.|
347