js-apis-resourceschedule-workScheduler.md 18.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
# Work Scheduler

The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints.

The system executes Work Scheduler tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.

>  **NOTE**
>
>  - 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.
>  - The APIs of this module can be used only in the stage model.
>  - For details about the restrictions, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks).


## Modules to Import

```js
import workScheduler from '@ohos.resourceschedule.workScheduler';
```

## workScheduler.startWork
startWork(work: WorkInfo): void

Instructs the **WorkSchedulerService** to add the specified task to the execution queue.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Parameters**

| Name | Type                   | Mandatory  | Description            |
| ---- | --------------------- | ---- | -------------- |
| work | [WorkInfo](#workinfo) | Yes   | Task to be added to the execution queue.|

**Error codes**

For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).

| ID | Error Message            |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. |
| 9700005 | StartWork failed. |


**Example**

```js
  let workInfo = {
      workId: 1,
      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
      isRepeat: false,
      isPersisted: true,
      bundleName: "com.example.myapplication",
      abilityName: "MyExtension",
      parameters: {
          mykey0: 1,
          mykey1: "string value",
          mykey2: true,
          mykey3: 1.5
      }
  }
  try{
    workScheduler.startWork(workInfo);
    console.info('workschedulerLog startWork success');
  } catch (error) {
    console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`);
  }
```

## workScheduler.stopWork
stopWork(work: WorkInfo, needCancel?: boolean): void

Instructs the **WorkSchedulerService** to stop the specified task.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Parameters**

| Name       | Type                   | Mandatory  | Description        |
| ---------- | --------------------- | ---- | ---------- |
| work       | [WorkInfo](#workinfo) | Yes   | Task to stop. |
| needCancel | boolean               | Yes   | Whether to cancel the task.|

**Error codes**

For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).

| ID | Error Message            |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. |

**Example**

```js
  let workInfo = {
      workId: 1,
      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
      isRepeat: false,
      isPersisted: true,
      bundleName: "com.example.myapplication",
      abilityName: "MyExtension",
      parameters: {
          mykey0: 1,
          mykey1: "string value",
          mykey2: true,
          mykey3: 1.5
      }
     }
  try{
    workScheduler.stopWork(workInfo, false);
    console.info('workschedulerLog stopWork success');
  } catch (error) {
    console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`);
  }
```

## workScheduler.getWorkStatus:callback
getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void

Obtains the latest task status. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Parameters**

| Name     | Type                                   | Mandatory  | Description                                      |
| -------- | ------------------------------------- | ---- | ---------------------------------------- |
| workId   | number                                | Yes   | Task ID.                                |
| 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.|

**Error codes**

For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).

| ID | Error Message            |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. |

**Example**

```js
  try{
    workScheduler.getWorkStatus(50, (error, res) => {
      if (error) {
        console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
      } else {
        for (let item in res) {
          console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
        }
      }
    });
  } catch (error) {
    console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
  }
```

## workScheduler.getWorkStatus:promise
getWorkStatus(workId: number): Promise\<WorkInfo>

Obtains the latest task status. This API uses a promise to return the result.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Parameters**

| Name   | Type    | Mandatory  | Description      |
| ------ | ------ | ---- | -------- |
| workId | number | Yes   | Task ID.|

**Return value**

| Type                             | Description                                      |
| ------------------------------- | ---------------------------------------- |
| 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.|

**Error codes**

For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).

| ID | Error Message            |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. |

**Example**

```js
  try{
    workScheduler.getWorkStatus(50).then((res) => {
      for (let item in res) {
        console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
      }
    }).catch((error) => {
      console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
    })
  } catch (error) {
    console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
  }
```

## workScheduler.obtainAllWorks:callback
obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>

Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Parameters**

| Name     | Type                  | Mandatory  | Description                             |
| -------- | -------------------- | ---- | ------------------------------- |
| callback | AsyncCallback\<void> | Yes   | Callback used to return the result. All tasks associated with the current application.|

**Return value**

| Type                           | Description             |
| ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.|

**Error codes**

For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).

| ID | Error Message            |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |

**Example**

```js
  try{
    workScheduler.obtainAllWorks((error, res) =>{
      if (error) {
        console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
      } else {
        console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
      }
    });
  } catch (error) {
    console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
  }
```

## workScheduler.obtainAllWorks:promise
obtainAllWorks(): Promise<Array\<WorkInfo>>

Obtains all tasks associated with this application. This API uses a promise to return the result.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Return value**

| Type                                    | Description                            |
| -------------------------------------- | ------------------------------ |
| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return the result. All tasks associated with the current application.|

**Error codes**

For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).

| ID | Error Message            |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |

**Example**

```js
  try{
    workScheduler.obtainAllWorks().then((res) => {
      console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
    }).catch((error) => {
      console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
    })
  } catch (error) {
    console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
  }
```

## workScheduler.stopAndClearWorks
stopAndClearWorks(): void

Stops and cancels all tasks associated with the current application.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Error codes**

For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).

| ID | Error Message            |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |

**Example**

```js
  try{
    workScheduler.stopAndClearWorks();
    console.info(`workschedulerLog stopAndClearWorks success`);
  } catch (error) {
    console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`);
  }
```

## workScheduler.isLastWorkTimeOut:callback
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean

Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Parameters**

| Name     | Type                  | Mandatory  | Description                                      |
| -------- | -------------------- | ---- | ---------------------------------------- |
| workId   | number               | Yes   | Task ID.                                |
| 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.|

**Return value**

| Type     | Description                                      |
| ------- | ---------------------------------------- |
| boolean | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|

**Error codes**

For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).

| ID | Error Message            |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |

**Example**

```js
  try{
    workScheduler.isLastWorkTimeOut(500, (error, res) =>{
      if (error) {
        console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
      } else {
        console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
      }
    });
  } catch (error) {
    console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
  }
```

## workScheduler.isLastWorkTimeOut:promise
isLastWorkTimeOut(workId: number): Promise\<boolean>

Checks whether the last execution of the specified task timed out. This API uses a promise to return the result.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Parameters**

| Name   | Type    | Mandatory  | Description      |
| ------ | ------ | ---- | -------- |
| workId | number | Yes   | Task ID.|

**Return value**

| Type               | Description                                      |
| ----------------- | ---------------------------------------- |
| Promise\<boolean> | Promise used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|

**Error codes**

For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).

| ID | Error Message            |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |

**Example**

```js
  try{
    workScheduler.isLastWorkTimeOut(500)
      .then(res => {
        console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
      })
      .catch(error =>  {
        console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
      });
  } catch (error) {
    console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
  }
```

## WorkInfo
Provides 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).

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

| Name            | Type                               | Mandatory  | Description              |
| --------------- | --------------------------------- | ---- | ---------------- |
| workId          | number                            | Yes   | Task ID.         |
| bundleName      | string                            | Yes   | Name of the Work Scheduler task bundle.          |
| abilityName     | string                            | Yes   | Name of the component to be notified by a Work Scheduler callback.|
| networkType     | [NetworkType](#networktype)       | No   | Network type.            |
| isCharging      | boolean                           | No   | Whether the device is charging.            |
| chargerType     | [ChargingType](#chargingtype)     | No   | Charging type.            |
| batteryLevel    | number                            | No   | Battery level.              |
| batteryStatus   | [BatteryStatus](#batterystatus)   | No   | Battery status.            |
| storageRequest  | [StorageRequest](#storagerequest) | No   | Storage status.            |
| isRepeat        | boolean                           | No   | Whether the task is repeated.          |
| repeatCycleTime | number                            | No   | Repeat interval.            |
| repeatCount     | number                            | No   | Number of repeat times.            |
| isPersisted     | boolean                           | No   | Whether to enable persistent storage for the task.       |
| isDeepIdle      | boolean                           | No   | Whether the device needs to enter the idle state.    |
| idleWaitTime    | number                            | No   | Time to wait in the idle state.          |
| parameters      | {[key: string]: any}              | No   | Carried parameters.          |

## NetworkType
Enumerates the network types that can trigger the task.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

| Name                    | Description                     |
| ---------------------- | ----------------------- |
| NETWORK_TYPE_ANY       | Any network type.    |
| NETWORK_TYPE_MOBILE    | Mobile network.   |
| NETWORK_TYPE_WIFI      | Wi-Fi network.  |
| NETWORK_TYPE_BLUETOOTH | Bluetooth network.|
| NETWORK_TYPE_WIFI_P2P  | Wi-Fi P2P network. |
| NETWORK_TYPE_ETHERNET  | Ethernet.       |

## ChargingType
Enumerates the charging types that can trigger the task.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

| Name                       | Description                  |
| ------------------------- | -------------------- |
| CHARGING_PLUGGED_ANY      | Any charging type.|
| CHARGING_PLUGGED_AC       | DC charging.   |
| CHARGING_PLUGGED_USB      | USB charging.    |
| CHARGING_PLUGGED_WIRELESS | Wireless charging.   |

## BatteryStatus
Enumerates the battery states that can trigger the task.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

| Name                        | Description                        |
| -------------------------- | -------------------------- |
| BATTERY_STATUS_LOW         | A low battery alert is displayed.            |
| BATTERY_STATUS_OKAY        | The battery level is restored from low to normal.      |
| BATTERY_STATUS_LOW_OR_OKAY | The battery level is restored from low to normal, or a low battery alert is displayed.|

## StorageRequest
Enumerates the storage states that can trigger the task.

**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

| Name                       | Description                            |
| ------------------------- | ------------------------------ |
| STORAGE_LEVEL_LOW         | The storage space is insufficient.              |
| STORAGE_LEVEL_OKAY        | The storage space is restored from insufficient to normal.        |
| STORAGE_LEVEL_LOW_OR_OKAY | The storage space is restored from insufficient to normal, or the storage space is insufficient.|