• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.resourceschedule.workScheduler (Deferred Task Scheduling)
2
3The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks. You can use the APIs to register tasks that do not have high requirements on real-time performance as deferred tasks. The system schedules and executes the deferred tasks at an appropriate time, subject to the storage space, power consumption, and more.
4
5>  **NOTE**
6>
7>  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.
8>
9>  The APIs of this module can be used only in the stage model.
10
11## Modules to Import
12
13```ts
14import workScheduler from '@ohos.resourceschedule.workScheduler';
15```
16
17## workScheduler.startWork
18
19startWork(work: WorkInfo): void
20
21Starts a deferred task.
22
23**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
24
25**Parameters**
26
27| Name | Type                   | Mandatory  | Description            |
28| ---- | --------------------- | ---- | -------------- |
29| work | [WorkInfo](#workinfo) | Yes   | Deferred task to start.|
30
31**Error codes**
32
33For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
34
35| ID | Error Message            |
36| ---- | --------------------- |
37| 9700001 | Memory operation failed. |
38| 9700002 | Parcel operation failed. |
39| 9700003 | System service operation failed. |
40| 9700004 | Check workInfo failed. |
41| 9700005 | StartWork failed. |
42
43**Example**
44
45```ts
46  import { BusinessError } from '@ohos.base';
47
48  let workInfo: workScheduler.WorkInfo = {
49      workId: 1,
50      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
51      isRepeat: false,
52      isPersisted: true,
53      bundleName: "com.example.myapplication",
54      abilityName: "MyExtension",
55      parameters: {
56          mykey0: 1,
57          mykey1: "string value",
58          mykey2: true,
59          mykey3: 1.5
60      }
61  }
62  try{
63    workScheduler.startWork(workInfo);
64    console.info('workschedulerLog startWork success');
65  } catch (error) {
66    console.error(`workschedulerLog startwork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
67  }
68```
69
70## workScheduler.stopWork
71
72stopWork(work: WorkInfo, needCancel?: boolean): void
73
74Stops a deferred task.
75
76**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
77
78**Parameters**
79
80| Name       | Type                   | Mandatory  | Description        |
81| ---------- | --------------------- | ---- | ---------- |
82| work       | [WorkInfo](#workinfo) | Yes   | Deferred task to stop.|
83| needCancel | boolean               | No   | Whether to clear the task while stopping it.<br>The value **true** means to clear the task while stopping it, and **false** means to stop the task only. The default value is **false**.|
84
85**Error codes**
86
87For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
88
89| ID | Error Message            |
90| ---- | --------------------- |
91| 9700001 | Memory operation failed. |
92| 9700002 | Parcel operation failed. |
93| 9700003 | System service operation failed. |
94| 9700004 | Check workInfo failed. |
95
96**Example**
97
98```ts
99  import { BusinessError } from '@ohos.base';
100
101  let workInfo: workScheduler.WorkInfo = {
102      workId: 1,
103      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
104      isRepeat: false,
105      isPersisted: true,
106      bundleName: "com.example.myapplication",
107      abilityName: "MyExtension",
108      parameters: {
109          mykey0: 1,
110          mykey1: "string value",
111          mykey2: true,
112          mykey3: 1.5
113      }
114     }
115  try{
116    workScheduler.stopWork(workInfo, false);
117    console.info('workschedulerLog stopWork success');
118  } catch (error) {
119    console.error(`workschedulerLog stopWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
120  }
121```
122
123## workScheduler.getWorkStatus
124
125getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void
126
127Obtains the information a deferred task. This API uses an asynchronous callback to return the result.
128
129**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
130
131**Parameters**
132
133| Name     | Type                                   | Mandatory  | Description                                      |
134| -------- | ------------------------------------- | ---- | ---------------------------------------- |
135| workId   | number                                | Yes   | ID of the deferred task.                                |
136| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes   | Callback used to return the result. If **workId** is valid, the task information obtained from WorkSchedulerService is returned. Otherwise, an exception is thrown.|
137
138**Error codes**
139
140For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
141
142| ID | Error Message            |
143| ---- | --------------------- |
144| 9700001 | Memory operation failed. |
145| 9700002 | Parcel operation failed. |
146| 9700003 | System service operation failed. |
147| 9700004 | Check workInfo failed. |
148
149**Example**
150
151```ts
152  import { BusinessError } from '@ohos.base';
153
154  workScheduler.getWorkStatus(50, (error: BusinessError, res: workScheduler.WorkInfo) => {
155    if (error) {
156      console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
157    } else {
158      console.info(`workschedulerLog getWorkStatus success, ${JSON.stringify(res)}`);
159    }
160  });
161```
162
163## workScheduler.getWorkStatus
164
165getWorkStatus(workId: number): Promise\<WorkInfo>
166
167Obtains the information a deferred task. This API uses a promise to return the result.
168
169**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
170
171**Parameters**
172
173| Name   | Type    | Mandatory  | Description      |
174| ------ | ------ | ---- | -------- |
175| workId | number | Yes   | ID of the deferred task.|
176
177**Return value**
178
179| Type                             | Description                                      |
180| ------------------------------- | ---------------------------------------- |
181| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If **workId** is valid, the task information obtained from WorkSchedulerService is returned. Otherwise, an exception is thrown.|
182
183**Error codes**
184
185For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
186
187| ID | Error Message            |
188| ---- | --------------------- |
189| 9700001 | Memory operation failed. |
190| 9700002 | Parcel operation failed. |
191| 9700003 | System service operation failed. |
192| 9700004 | Check workInfo failed. |
193
194**Example**
195
196```ts
197  import { BusinessError } from '@ohos.base';
198
199  workScheduler.getWorkStatus(50).then((res: workScheduler.WorkInfo) => {
200    console.info(`workschedulerLog getWorkStatus success, ${JSON.stringify(res)}`);
201  }).catch((error: BusinessError) => {
202    console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
203  })
204```
205
206## workScheduler.obtainAllWorks<sup>deprecated<sup>
207
208obtainAllWorks(callback : AsyncCallback\<void>) : Array\<WorkInfo>
209> This API is deprecated since API version 10. You are advised to use [workScheduler.obtainAllWorks<sup>10+<sup>](#workschedulerobtainallworks10) instead.
210
211Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.
212
213**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
214
215**Parameters**
216
217| Name     | Type                  | Mandatory  | Description                             |
218| -------- | -------------------- | ---- | ------------------------------- |
219| callback |  AsyncCallback\<void> | Yes   | Callback used to return the result. If all the deferred tasks are obtained, **err** is **undefined**. Otherwise, **err** is an error object.|
220
221**Error codes**
222
223For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
224
225| ID | Error Message            |
226| ---- | --------------------- |
227| 9700001 | Memory operation failed. |
228| 9700002 | Parcel operation failed. |
229| 9700003 | System service operation failed. |
230
231## workScheduler.obtainAllWorks<sup>10+<sup>
232
233obtainAllWorks(callback : AsyncCallback&lt;Array&lt;WorkInfo&gt;&gt;): void
234
235Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.
236
237**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
238
239**Parameters**
240
241| Name     | Type                  | Mandatory  | Description                             |
242| -------- | -------------------- | ---- | ------------------------------- |
243| callback |  AsyncCallback&lt;Array&lt;WorkInfo&gt;&gt; | Yes   | Callback used to return the result. If all the deferred tasks are obtained, **err** is **undefined**. Otherwise, **err** is an error object.|
244
245**Error codes**
246
247For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
248
249| ID | Error Message            |
250| ---- | --------------------- |
251| 9700001 | Memory operation failed. |
252| 9700002 | Parcel operation failed. |
253| 9700003 | System service operation failed. |
254
255**Example**
256
257```ts
258  import { BusinessError } from '@ohos.base';
259
260  workScheduler.obtainAllWorks((error: BusinessError, res: Array<workScheduler.WorkInfo>) =>{
261    if (error) {
262      console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
263    } else {
264      console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
265    }
266  });
267```
268
269## workScheduler.obtainAllWorks
270
271obtainAllWorks(): Promise\<Array\<WorkInfo>>
272
273Obtains all the deferred tasks. This API uses a promise to return the result.
274
275**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
276
277**Return value**
278
279| Type                                    | Description                            |
280| -------------------------------------- | ------------------------------ |
281| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return all the deferred tasks.|
282
283**Error codes**
284
285For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
286
287| ID | Error Message            |
288| ---- | --------------------- |
289| 9700001 | Memory operation failed. |
290| 9700002 | Parcel operation failed. |
291| 9700003 | System service operation failed. |
292
293**Example**
294
295```ts
296  import { BusinessError } from '@ohos.base';
297
298  workScheduler.obtainAllWorks().then((res: Array<workScheduler.WorkInfo>) => {
299    console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
300  }).catch((error: BusinessError) => {
301    console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
302  })
303```
304
305## workScheduler.stopAndClearWorks
306
307stopAndClearWorks(): void
308
309Stops and clears all the deferred tasks.
310
311**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
312
313**Error codes**
314
315For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
316
317| ID | Error Message            |
318| ---- | --------------------- |
319| 9700001 | Memory operation failed. |
320| 9700002 | Parcel operation failed. |
321| 9700003 | System service operation failed. |
322
323**Example**
324
325```ts
326  import { BusinessError } from '@ohos.base';
327
328  try{
329    workScheduler.stopAndClearWorks();
330    console.info(`workschedulerLog stopAndClearWorks success`);
331  } catch (error) {
332    console.error(`workschedulerLog stopAndClearWorks failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
333  }
334```
335
336## workScheduler.isLastWorkTimeOut<sup>deprecated<sup>
337
338isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
339
340> This API is deprecated since API version 10. You are advised to use [workScheduler.isLastWorkTimeOut<sup>10+<sup>](#workschedulerislastworktimeout10) instead.
341
342Checks whether the last execution of a task timed out. This API uses an asynchronous callback to return the result.
343
344**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
345
346**Parameters**
347
348| Name     | Type                  | Mandatory  | Description                                      |
349| -------- | -------------------- | ---- | ---------------------------------------- |
350| workId   | number               | Yes   | ID of the deferred task.                                |
351| callback | AsyncCallback\<void> | Yes   | Callback used to return the result.|
352
353**Error codes**
354
355For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
356
357| ID | Error Message            |
358| ---- | --------------------- |
359| 9700001 | Memory operation failed. |
360| 9700002 | Parcel operation failed. |
361| 9700003 | System service operation failed. |
362| 9700004 | Check workInfo failed. |
363
364## workScheduler.isLastWorkTimeOut<sup>10+<sup>
365
366isLastWorkTimeOut(workId: number, callback : AsyncCallback\<boolean>): void
367
368Checks whether the last execution of a task timed out. This API uses an asynchronous callback to return the result.
369
370**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
371
372**Parameters**
373
374| Name     | Type                  | Mandatory  | Description                                      |
375| -------- | -------------------- | ---- | ---------------------------------------- |
376| workId   | number               | Yes   | ID of the deferred task.                                |
377| callback | AsyncCallback\<boolean> | Yes   | Callback used to return the result.|
378
379**Error codes**
380
381For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
382
383| ID | Error Message            |
384| ---- | --------------------- |
385| 9700001 | Memory operation failed. |
386| 9700002 | Parcel operation failed. |
387| 9700003 | System service operation failed. |
388| 9700004 | Check workInfo failed. |
389
390**Example**
391
392```ts
393  import { BusinessError } from '@ohos.base';
394
395  workScheduler.isLastWorkTimeOut(500, (error: BusinessError, res: boolean) =>{
396    if (error) {
397      console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
398    } else {
399      console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
400    }
401  });
402```
403
404## workScheduler.isLastWorkTimeOut
405
406isLastWorkTimeOut(workId: number): Promise\<boolean>
407
408Checks whether the last execution of a task timed out. This API uses a promise to return the result.
409
410**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
411
412**Parameters**
413
414| Name   | Type    | Mandatory  | Description      |
415| ------ | ------ | ---- | -------- |
416| workId | number | Yes   | ID of the deferred task.|
417
418**Return value**
419
420| Type               | Description                                      |
421| ----------------- | ---------------------------------------- |
422| Promise\<boolean> | Promise used to return the result. The value **true** means that the last execution of the specified task times out, and **false** means the opposite.|
423
424**Error codes**
425
426For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
427
428| ID | Error Message            |
429| ---- | --------------------- |
430| 9700001 | Memory operation failed. |
431| 9700002 | Parcel operation failed. |
432| 9700003 | System service operation failed. |
433| 9700004 | Check workInfo failed. |
434
435**Example**
436
437```ts
438  import { BusinessError } from '@ohos.base';
439
440  workScheduler.isLastWorkTimeOut(500)
441    .then((res: boolean) => {
442      console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
443    })
444    .catch((error: BusinessError) =>  {
445      console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
446    });
447```
448
449## WorkInfo
450
451Defines the information about the deferred task.
452
453**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
454
455| Name            | Type                               | Mandatory  | Description              |
456| --------------- | --------------------------------- | ---- | ---------------- |
457| workId          | number                            | Yes   | ID of the deferred task.         |
458| bundleName      | string                            | Yes   | Bundle name of the application that requests the task.          |
459| abilityName     | string                            | Yes   | Name of the component to be notified by a deferred task scheduling callback.|
460| networkType     | [NetworkType](#networktype)       | No   | Network type.            |
461| 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.|
462| chargerType     | [ChargingType](#chargingtype)     | No   | Charging type.            |
463| batteryLevel    | number                            | No   | Battery level.             |
464| batteryStatus   | [BatteryStatus](#batterystatus)   | No   | Battery status.            |
465| storageRequest  | [StorageRequest](#storagerequest) | No   | Storage status.            |
466| isRepeat        | boolean                           | No   | Whether the task is repeated.<br>The value** true** means that the task is repeated, and **false** means the opposite.|
467| repeatCycleTime | number                            | No   | Repeat interval, in milliseconds.            |
468| repeatCount     | number                            | No   | Number of repeat times.            |
469| isPersisted     | boolean                           | No   | Whether to enable persistent storage for the task.<br>The value **true** means to enable persistent storage for the task, and **false** means the opposite.|
470| 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.  |
471| idleWaitTime    | number                            | No   | Time to wait in the idle state before triggering deferred task scheduling, in milliseconds.          |
472| parameters      | Record<string, number \| string \| boolean>  | No   | Carried parameters.|
473
474## NetworkType
475
476Enumerates the network types that can trigger deferred task scheduling.
477
478**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
479
480| Name                    | Value | Description                     |
481| ---------------------- | ---- | ----------------------- |
482| NETWORK_TYPE_ANY       | 0    | Any network type.    |
483| NETWORK_TYPE_MOBILE    | 1    | Mobile network.   |
484| NETWORK_TYPE_WIFI      | 2    | Wi-Fi network.  |
485| NETWORK_TYPE_BLUETOOTH | 3    | Bluetooth network.|
486| NETWORK_TYPE_WIFI_P2P  | 4    | Wi-Fi P2P network. |
487| NETWORK_TYPE_ETHERNET  | 5    | Ethernet.       |
488
489## ChargingType
490
491Enumerates the charging types that can trigger deferred task scheduling.
492
493**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
494
495| Name                       | Value | Description                  |
496| ------------------------- | ---- | -------------------- |
497| CHARGING_PLUGGED_ANY      | 0    | Any charging type.|
498| CHARGING_PLUGGED_AC       | 1    | DC charging.   |
499| CHARGING_PLUGGED_USB      | 2    | USB charging.    |
500| CHARGING_PLUGGED_WIRELESS | 3    | Wireless charging.   |
501
502## BatteryStatus
503
504Enumerates the battery statuses that can trigger deferred task scheduling.
505
506**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
507
508| Name                        | Value | Description                        |
509| -------------------------- | ---- | -------------------------- |
510| BATTERY_STATUS_LOW         | 0    | A low battery alert is displayed.            |
511| BATTERY_STATUS_OKAY        | 1    | The battery level is restored from low to normal.      |
512| BATTERY_STATUS_LOW_OR_OKAY | 2    | The battery level is restored from low to normal, or a low battery alert is displayed.|
513
514## StorageRequest
515
516Enumerates the storage statuses that can trigger deferred task scheduling.
517
518**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
519
520| Name                       | Value | Description                            |
521| ------------------------- | ---- | ------------------------------ |
522| STORAGE_LEVEL_LOW         | 0    | The storage space is insufficient.              |
523| STORAGE_LEVEL_OKAY        | 1    | The storage space is restored from insufficient to normal.        |
524| STORAGE_LEVEL_LOW_OR_OKAY | 2    | The storage space is insufficient, or the storage space is restored from insufficient to normal.|
525