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