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