1# @ohos.resourceschedule.workScheduler (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> - The APIs of this module can be used only in the stage model. 11> - For details about the restrictions, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks). 12 13 14## Modules to Import 15 16```js 17import workScheduler from '@ohos.resourceschedule.workScheduler'; 18``` 19 20## workScheduler.startWork 21startWork(work: WorkInfo): void 22 23Instructs the **WorkSchedulerService** to add the specified task to the execution queue. 24 25**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 26 27**Parameters** 28 29| Name | Type | Mandatory | Description | 30| ---- | --------------------- | ---- | -------------- | 31| work | [WorkInfo](#workinfo) | Yes | Task to be added to the execution queue.| 32 33**Error codes** 34 35For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md). 36 37| ID | Error Message | 38| ---- | --------------------- | 39| 9700001 | Memory operation failed. | 40| 9700002 | Parcel operation failed. | 41| 9700003 | System service operation failed. | 42| 9700004 | Check workInfo failed. | 43| 9700005 | StartWork failed. | 44 45 46**Example** 47 48```js 49 let 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.code} message is ${error.message}`); 68 } 69``` 70 71## workScheduler.stopWork 72stopWork(work: WorkInfo, needCancel?: boolean): void 73 74Instructs the **WorkSchedulerService** to stop the specified task. 75 76**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 77 78**Parameters** 79 80| Name | Type | Mandatory | Description | 81| ---------- | --------------------- | ---- | ---------- | 82| work | [WorkInfo](#workinfo) | Yes | Task to stop. | 83| needCancel | boolean | No | Whether to cancel the task.| 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```js 99 let workInfo = { 100 workId: 1, 101 batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, 102 isRepeat: false, 103 isPersisted: true, 104 bundleName: "com.example.myapplication", 105 abilityName: "MyExtension", 106 parameters: { 107 mykey0: 1, 108 mykey1: "string value", 109 mykey2: true, 110 mykey3: 1.5 111 } 112 } 113 try{ 114 workScheduler.stopWork(workInfo, false); 115 console.info('workschedulerLog stopWork success'); 116 } catch (error) { 117 console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`); 118 } 119``` 120 121## workScheduler.getWorkStatus:callback 122getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void 123 124Obtains the latest task status. This API uses an asynchronous callback to return the result. 125 126**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 127 128**Parameters** 129 130| Name | Type | Mandatory | Description | 131| -------- | ------------------------------------- | ---- | ---------------------------------------- | 132| workId | number | Yes | Task ID. | 133| 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; throws an exception otherwise. | 134 135**Error codes** 136 137For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md). 138 139| ID | Error Message | 140| ---- | --------------------- | 141| 9700001 | Memory operation failed. | 142| 9700002 | Parcel operation failed. | 143| 9700003 | System service operation failed. | 144| 9700004 | Check workInfo failed. | 145 146**Example** 147 148```js 149 try{ 150 workScheduler.getWorkStatus(50, (error, res) => { 151 if (error) { 152 console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); 153 } else { 154 for (let item in res) { 155 console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); 156 } 157 } 158 }); 159 } catch (error) { 160 console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); 161 } 162``` 163 164## workScheduler.getWorkStatus:promise 165getWorkStatus(workId: number): Promise\<WorkInfo> 166 167Obtains the latest task status. 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 | Task ID.| 176 177**Return value** 178 179| Type | Description | 180| ------------------------------- | ---------------------------------------- | 181| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; throws an exception otherwise. | 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```js 197 try{ 198 workScheduler.getWorkStatus(50).then((res) => { 199 for (let item in res) { 200 console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); 201 } 202 }).catch((error) => { 203 console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); 204 }) 205 } catch (error) { 206 console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); 207 } 208``` 209 210## workScheduler.obtainAllWorks:callback 211obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo> 212 213Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result. 214 215**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 216 217**Parameters** 218 219| Name | Type | Mandatory | Description | 220| -------- | -------------------- | ---- | ------------------------------- | 221| callback | AsyncCallback\<void> | Yes | Callback used to return the result. All tasks associated with the current application.| 222 223**Return value** 224 225| Type | Description | 226| ----------------------------- | --------------- | 227| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.| 228 229**Error codes** 230 231For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md). 232 233| ID | Error Message | 234| ---- | --------------------- | 235| 9700001 | Memory operation failed. | 236| 9700002 | Parcel operation failed. | 237| 9700003 | System service operation failed. | 238 239**Example** 240 241```js 242 try{ 243 workScheduler.obtainAllWorks((error, res) =>{ 244 if (error) { 245 console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); 246 } else { 247 console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); 248 } 249 }); 250 } catch (error) { 251 console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); 252 } 253``` 254 255## workScheduler.obtainAllWorks:promise 256obtainAllWorks(): Promise<Array\<WorkInfo>> 257 258Obtains all tasks associated with this application. This API uses a promise to return the result. 259 260**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 261 262**Return value** 263 264| Type | Description | 265| -------------------------------------- | ------------------------------ | 266| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return the result. All tasks associated with the current application.| 267 268**Error codes** 269 270For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md). 271 272| ID | Error Message | 273| ---- | --------------------- | 274| 9700001 | Memory operation failed. | 275| 9700002 | Parcel operation failed. | 276| 9700003 | System service operation failed. | 277 278**Example** 279 280```js 281 try{ 282 workScheduler.obtainAllWorks().then((res) => { 283 console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); 284 }).catch((error) => { 285 console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); 286 }) 287 } catch (error) { 288 console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); 289 } 290``` 291 292## workScheduler.stopAndClearWorks 293stopAndClearWorks(): void 294 295Stops and cancels all tasks associated with the current application. 296 297**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 298 299**Error codes** 300 301For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md). 302 303| ID | Error Message | 304| ---- | --------------------- | 305| 9700001 | Memory operation failed. | 306| 9700002 | Parcel operation failed. | 307| 9700003 | System service operation failed. | 308 309**Example** 310 311```js 312 try{ 313 workScheduler.stopAndClearWorks(); 314 console.info(`workschedulerLog stopAndClearWorks success`); 315 } catch (error) { 316 console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`); 317 } 318``` 319 320## workScheduler.isLastWorkTimeOut:callback 321isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean 322 323Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result. 324 325**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 326 327**Parameters** 328 329| Name | Type | Mandatory | Description | 330| -------- | -------------------- | ---- | ---------------------------------------- | 331| workId | number | Yes | Task ID. | 332| 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.| 333 334**Return value** 335 336| Type | Description | 337| ------- | ---------------------------------------- | 338| boolean | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| 339 340**Error codes** 341 342For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md). 343 344| ID | Error Message | 345| ---- | --------------------- | 346| 9700001 | Memory operation failed. | 347| 9700002 | Parcel operation failed. | 348| 9700003 | System service operation failed. | 349| 9700004 | Check workInfo failed. | 350 351**Example** 352 353```js 354 try{ 355 workScheduler.isLastWorkTimeOut(500, (error, res) =>{ 356 if (error) { 357 console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); 358 } else { 359 console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); 360 } 361 }); 362 } catch (error) { 363 console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); 364 } 365``` 366 367## workScheduler.isLastWorkTimeOut:promise 368isLastWorkTimeOut(workId: number): Promise\<boolean> 369 370Checks whether the last execution of the specified task timed out. This API uses a promise to return the result. 371 372**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 373 374**Parameters** 375 376| Name | Type | Mandatory | Description | 377| ------ | ------ | ---- | -------- | 378| workId | number | Yes | Task ID.| 379 380**Return value** 381 382| Type | Description | 383| ----------------- | ---------------------------------------- | 384| Promise\<boolean> | Promise used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| 385 386**Error codes** 387 388For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md). 389 390| ID | Error Message | 391| ---- | --------------------- | 392| 9700001 | Memory operation failed. | 393| 9700002 | Parcel operation failed. | 394| 9700003 | System service operation failed. | 395| 9700004 | Check workInfo failed. | 396 397**Example** 398 399```js 400 try{ 401 workScheduler.isLastWorkTimeOut(500) 402 .then(res => { 403 console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); 404 }) 405 .catch(error => { 406 console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); 407 }); 408 } catch (error) { 409 console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); 410 } 411``` 412 413## WorkInfo 414Provides detailed information about the task. For details about the constraints on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks). 415 416**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 417 418| Name | Type | Mandatory | Description | 419| --------------- | --------------------------------- | ---- | ---------------- | 420| workId | number | Yes | Task ID. | 421| bundleName | string | Yes | Name of the Work Scheduler task bundle. | 422| abilityName | string | Yes | Name of the component to be notified by a Work Scheduler callback.| 423| networkType | [NetworkType](#networktype) | No | Network type. | 424| isCharging | boolean | No | Whether the device is charging. | 425| chargerType | [ChargingType](#chargingtype) | No | Charging type. | 426| batteryLevel | number | No | Battery level. | 427| batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. | 428| storageRequest | [StorageRequest](#storagerequest) | No | Storage status. | 429| isRepeat | boolean | No | Whether the task is repeated. | 430| repeatCycleTime | number | No | Repeat interval. | 431| repeatCount | number | No | Number of repeat times. | 432| isPersisted | boolean | No | Whether to enable persistent storage for the task. | 433| isDeepIdle | boolean | No | Whether the device needs to enter the idle state. | 434| idleWaitTime | number | No | Time to wait in the idle state. | 435| parameters | {[key: string]: number | string | boolean} | No | Carried parameters. | 436 437## NetworkType 438Enumerates the network types that can trigger the task. 439 440**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 441 442| Name | Value | Description | 443| ---------------------- | ---- | ----------------------- | 444| NETWORK_TYPE_ANY | 0 | Any network type. | 445| NETWORK_TYPE_MOBILE | 1 | Mobile network. | 446| NETWORK_TYPE_WIFI | 2 | Wi-Fi network. | 447| NETWORK_TYPE_BLUETOOTH | 3 | Bluetooth network.| 448| NETWORK_TYPE_WIFI_P2P | 4 | Wi-Fi P2P network. | 449| NETWORK_TYPE_ETHERNET | 5 | Ethernet. | 450 451## ChargingType 452Enumerates the charging types that can trigger the task. 453 454**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 455 456| Name | Value | Description | 457| ------------------------- | ---- | -------------------- | 458| CHARGING_PLUGGED_ANY | 0 | Any charging type.| 459| CHARGING_PLUGGED_AC | 1 | DC charging. | 460| CHARGING_PLUGGED_USB | 2 | USB charging. | 461| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | 462 463## BatteryStatus 464Enumerates the battery states that can trigger the task. 465 466**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 467 468| Name | Value | Description | 469| -------------------------- | ---- | -------------------------- | 470| BATTERY_STATUS_LOW | 0 | A low battery alert is displayed. | 471| BATTERY_STATUS_OKAY | 1 | The battery level is restored from low to normal. | 472| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.| 473 474## StorageRequest 475Enumerates the storage states that can trigger the task. 476 477**System capability**: SystemCapability.ResourceSchedule.WorkScheduler 478 479| Name | Value | Description | 480| ------------------------- | ---- | ------------------------------ | 481| STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. | 482| STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. | 483| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is restored from insufficient to normal, or the storage space is insufficient.| 484