js-apis-workScheduler.md 14.1 KB
Newer Older
E
esterzhou 已提交
1 2
# Work Scheduler

E
ester.zhou 已提交
3 4 5 6 7 8 9 10
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.
E
ester.zhou 已提交
11
>  - For details about the constraints on the Work Scheduler usage, see [Work Scheduler Overview](../../task-management/work-scheduler-overview.md).
E
esterzhou 已提交
12 13 14 15


## Modules to Import

E
ester.zhou 已提交
16
```js
E
ester.zhou 已提交
17
import workScheduler from '@ohos.workScheduler';
E
esterzhou 已提交
18 19 20
```

## workScheduler.startWork
E
ester.zhou 已提交
21
startWork(work: WorkInfo): boolean
E
esterzhou 已提交
22 23 24

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

E
ester.zhou 已提交
25
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
26

E
ester.zhou 已提交
27
**Parameters**
E
esterzhou 已提交
28

E
ester.zhou 已提交
29 30 31
| Name | Type                   | Mandatory  | Description            |
| ---- | --------------------- | ---- | -------------- |
| work | [WorkInfo](#workinfo) | Yes   | Task to be added to the execution queue.|
E
esterzhou 已提交
32

E
ester.zhou 已提交
33
**Return value**
E
esterzhou 已提交
34

E
ester.zhou 已提交
35 36 37
| Type     | Description                              |
| ------- | -------------------------------- |
| boolean | Returns **true** if the task is added to the execution queue; returns **false** otherwise.|
E
esterzhou 已提交
38

E
ester.zhou 已提交
39
**Example**
E
esterzhou 已提交
40

E
ester.zhou 已提交
41
```js
E
ester.zhou 已提交
42 43 44 45 46 47
  let workInfo = {
      workId: 1,
      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
      isRepeat: false,
      isPersisted: true,
      bundleName: "com.example.myapplication",
E
ester.zhou 已提交
48 49 50 51 52 53 54
      abilityName: "MyExtension",
      parameters: {
          mykey0: 1,
          mykey1: "string value",
          mykey2: true,
          mykey3: 1.5
      }
E
ester.zhou 已提交
55 56
  }
  var res = workScheduler.startWork(workInfo);
E
ester.zhou 已提交
57
  console.info(`workschedulerLog res: ${res}`);
E
ester.zhou 已提交
58
```
E
esterzhou 已提交
59

E
ester.zhou 已提交
60
## workScheduler.stopWork
E
esterzhou 已提交
61 62 63 64
stopWork(work: WorkInfo, needCancel?: boolean): boolean

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

E
ester.zhou 已提交
65
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
66

E
ester.zhou 已提交
67
**Parameters**
E
esterzhou 已提交
68

E
ester.zhou 已提交
69 70 71 72
| Name       | Type                   | Mandatory  | Description        |
| ---------- | --------------------- | ---- | ---------- |
| work       | [WorkInfo](#workinfo) | Yes   | Task to stop. |
| needCancel | boolean               | Yes   | Whether to cancel the task.|
E
esterzhou 已提交
73

E
ester.zhou 已提交
74
**Return value**
E
esterzhou 已提交
75

E
ester.zhou 已提交
76 77 78
| Type     | Description                     |
| ------- | ----------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
E
esterzhou 已提交
79

E
ester.zhou 已提交
80
**Example**
E
esterzhou 已提交
81

E
ester.zhou 已提交
82
```js
E
ester.zhou 已提交
83 84 85 86 87 88
  let workInfo = {
      workId: 1,
      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
      isRepeat: false,
      isPersisted: true,
      bundleName: "com.example.myapplication",
E
ester.zhou 已提交
89 90 91 92 93 94 95
      abilityName: "MyExtension",
      parameters: {
          mykey0: 1,
          mykey1: "string value",
          mykey2: true,
          mykey3: 1.5
      }
E
ester.zhou 已提交
96 97
     }
  var res = workScheduler.stopWork(workInfo, false);
E
ester.zhou 已提交
98
  console.info(`workschedulerLog res: ${res}`);
E
ester.zhou 已提交
99
```
E
esterzhou 已提交
100

E
ester.zhou 已提交
101 102
## workScheduler.getWorkStatus
getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void
E
esterzhou 已提交
103

E
ester.zhou 已提交
104
Obtains the latest task status. This API uses an asynchronous callback to return the result.
E
esterzhou 已提交
105

E
ester.zhou 已提交
106
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
107

E
ester.zhou 已提交
108
**Parameters**
E
esterzhou 已提交
109

E
ester.zhou 已提交
110 111 112 113
| 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.|
E
esterzhou 已提交
114

E
ester.zhou 已提交
115
**Example**
E
esterzhou 已提交
116

E
ester.zhou 已提交
117
```js
E
ester.zhou 已提交
118 119
  workScheduler.getWorkStatus(50, (err, res) => {
    if (err) {
E
ester.zhou 已提交
120
      console.info(`workschedulerLog getWorkStatus failed, because: ${err.code}`);
E
ester.zhou 已提交
121 122
    } else {
      for (let item in res) {
E
ester.zhou 已提交
123
        console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
E
esterzhou 已提交
124
      }
E
ester.zhou 已提交
125 126 127
    }
  });
```
E
esterzhou 已提交
128 129

## workScheduler.getWorkStatus
E
ester.zhou 已提交
130
getWorkStatus(workId: number): Promise\<WorkInfo>
E
esterzhou 已提交
131

E
ester.zhou 已提交
132
Obtains the latest task status. This API uses a promise to return the result.
E
esterzhou 已提交
133

E
ester.zhou 已提交
134
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
135

E
ester.zhou 已提交
136
**Parameters**
E
esterzhou 已提交
137

E
ester.zhou 已提交
138 139 140
| Name   | Type    | Mandatory  | Description      |
| ------ | ------ | ---- | -------- |
| workId | number | Yes   | Task ID.|
E
esterzhou 已提交
141

E
ester.zhou 已提交
142
**Return value**
E
esterzhou 已提交
143

E
ester.zhou 已提交
144 145 146
| 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.|
E
esterzhou 已提交
147

E
ester.zhou 已提交
148
**Example**
E
esterzhou 已提交
149

E
ester.zhou 已提交
150
```js
E
ester.zhou 已提交
151 152
  workScheduler.getWorkStatus(50).then((res) => {
    for (let item in res) {
E
ester.zhou 已提交
153
      console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
E
ester.zhou 已提交
154 155
    }
  }).catch((err) => {
E
ester.zhou 已提交
156
    console.info(`workschedulerLog getWorkStatus failed, because: ${err.code}`);
E
ester.zhou 已提交
157 158
  })
```
E
esterzhou 已提交
159 160

## workScheduler.obtainAllWorks
E
ester.zhou 已提交
161
obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>
E
esterzhou 已提交
162

E
ester.zhou 已提交
163
Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result.
E
esterzhou 已提交
164

E
ester.zhou 已提交
165
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
166

E
ester.zhou 已提交
167
**Parameters**
E
esterzhou 已提交
168

E
ester.zhou 已提交
169 170
| Name     | Type                  | Mandatory  | Description                             |
| -------- | -------------------- | ---- | ------------------------------- |
E
ester.zhou 已提交
171
| callback | AsyncCallback\<void> | Yes   | Callback used to return all tasks associated with the current application. |
E
esterzhou 已提交
172

E
ester.zhou 已提交
173
**Return value**
E
esterzhou 已提交
174

E
ester.zhou 已提交
175 176 177
| Type                           | Description             |
| ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.|
E
esterzhou 已提交
178

E
ester.zhou 已提交
179
**Example**
E
esterzhou 已提交
180

E
ester.zhou 已提交
181
```js
E
ester.zhou 已提交
182 183
  workScheduler.obtainAllWorks((err, res) =>{
    if (err) {
E
ester.zhou 已提交
184
      console.info(`workschedulerLog obtainAllWorks failed, because: ${err.code}`);
E
ester.zhou 已提交
185
    } else {
E
ester.zhou 已提交
186
      console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
E
ester.zhou 已提交
187 188 189
    }
  });
```
E
esterzhou 已提交
190 191

## workScheduler.obtainAllWorks
E
ester.zhou 已提交
192
obtainAllWorks(): Promise<Array\<WorkInfo>>
E
esterzhou 已提交
193

E
ester.zhou 已提交
194
Obtains all tasks associated with this application. This API uses a promise to return the result.
E
esterzhou 已提交
195

E
ester.zhou 已提交
196
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
197

E
ester.zhou 已提交
198
**Return value**
E
esterzhou 已提交
199

E
ester.zhou 已提交
200 201
| Type                                    | Description                            |
| -------------------------------------- | ------------------------------ |
E
ester.zhou 已提交
202
| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return all tasks associated with the current application. |
E
esterzhou 已提交
203

E
ester.zhou 已提交
204
**Example**
E
esterzhou 已提交
205

E
ester.zhou 已提交
206
```js
E
ester.zhou 已提交
207
  workScheduler.obtainAllWorks().then((res) => {
E
ester.zhou 已提交
208
    console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
E
ester.zhou 已提交
209
  }).catch((err) => {
E
ester.zhou 已提交
210
    console.info(`workschedulerLog obtainAllWorks failed, because: ${err.code}`);
E
ester.zhou 已提交
211 212
  })
```
E
esterzhou 已提交
213 214 215 216 217 218

## workScheduler.stopAndClearWorks
stopAndClearWorks(): boolean

Stops and cancels all tasks associated with the current application.

E
ester.zhou 已提交
219 220 221
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Example**
E
esterzhou 已提交
222

E
ester.zhou 已提交
223
```js
E
ester.zhou 已提交
224
  let res = workScheduler.stopAndClearWorks();
E
ester.zhou 已提交
225
  console.info(`workschedulerLog res: ${res}`);
E
ester.zhou 已提交
226
```
E
esterzhou 已提交
227 228

## workScheduler.isLastWorkTimeOut
E
ester.zhou 已提交
229
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
E
esterzhou 已提交
230

E
ester.zhou 已提交
231
Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result.
E
esterzhou 已提交
232

E
ester.zhou 已提交
233
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
234

E
ester.zhou 已提交
235
**Parameters**
E
esterzhou 已提交
236

E
ester.zhou 已提交
237 238 239
| Name     | Type                  | Mandatory  | Description                                      |
| -------- | -------------------- | ---- | ---------------------------------------- |
| workId   | number               | Yes   | Task ID.                                |
E
ester.zhou 已提交
240
| 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.|
E
esterzhou 已提交
241

E
ester.zhou 已提交
242
**Return value**
E
esterzhou 已提交
243

E
ester.zhou 已提交
244 245
| Type     | Description                                      |
| ------- | ---------------------------------------- |
E
ester.zhou 已提交
246
| boolean | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
E
esterzhou 已提交
247

E
ester.zhou 已提交
248
**Example**
E
esterzhou 已提交
249

E
ester.zhou 已提交
250
```js
E
ester.zhou 已提交
251 252
  workScheduler.isLastWorkTimeOut(500, (err, res) =>{
    if (err) {
E
ester.zhou 已提交
253
      console.info(`workschedulerLog isLastWorkTimeOut failed, because: ${err.code}`);
E
ester.zhou 已提交
254
    } else {
E
ester.zhou 已提交
255
      console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
E
ester.zhou 已提交
256 257 258
    }
  });
```
E
esterzhou 已提交
259 260

## workScheduler.isLastWorkTimeOut
E
ester.zhou 已提交
261
isLastWorkTimeOut(workId: number): Promise\<boolean>
E
esterzhou 已提交
262

E
ester.zhou 已提交
263
Checks whether the last execution of the specified task timed out. This API uses a promise to return the result.
E
esterzhou 已提交
264

E
ester.zhou 已提交
265
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
266

E
ester.zhou 已提交
267
**Parameters**
E
esterzhou 已提交
268

E
ester.zhou 已提交
269 270 271
| Name   | Type    | Mandatory  | Description      |
| ------ | ------ | ---- | -------- |
| workId | number | Yes   | Task ID.|
E
esterzhou 已提交
272

E
ester.zhou 已提交
273
**Return value**
E
esterzhou 已提交
274

E
ester.zhou 已提交
275 276 277
| 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.|
E
esterzhou 已提交
278

E
ester.zhou 已提交
279
**Example**
E
esterzhou 已提交
280

E
ester.zhou 已提交
281
```js
E
ester.zhou 已提交
282 283
  workScheduler.isLastWorkTimeOut(500)
    .then(res => {
E
ester.zhou 已提交
284
      console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
E
esterzhou 已提交
285
    })
E
ester.zhou 已提交
286
    .catch(err =>  {
E
ester.zhou 已提交
287
      console.info(`workschedulerLog isLastWorkTimeOut failed, because: ${err.code}`);
E
ester.zhou 已提交
288 289
    });
```
E
esterzhou 已提交
290

E
ester.zhou 已提交
291
## WorkInfo
E
ester.zhou 已提交
292
Provides detailed information about the task. For details about the constraints on configuring **WorkInfo**, see [Work Scheduler Overview](../../task-management/work-scheduler-overview.md).
E
esterzhou 已提交
293

E
ester.zhou 已提交
294 295
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

E
ester.zhou 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
| 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.          |
E
ester.zhou 已提交
314 315

## NetworkType
E
esterzhou 已提交
316 317
Enumerates the network types that can trigger the task.

E
ester.zhou 已提交
318
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
319

E
ester.zhou 已提交
320 321 322 323 324 325 326 327
| Name                    | Default Value | Description                     |
| ---------------------- | ---- | ----------------------- |
| NETWORK_TYPE_ANY       | 0    | Any network type.    |
| NETWORK_TYPE_MOBILE    | 1    | Mobile network.   |
| NETWORK_TYPE_WIFI      | 2    | Wi-Fi network.  |
| NETWORK_TYPE_BLUETOOTH | 3    | Bluetooth network.|
| NETWORK_TYPE_WIFI_P2P  | 4    | Wi-Fi P2P network. |
| NETWORK_TYPE_ETHERNET  | 5    | Ethernet.       |
E
esterzhou 已提交
328

E
ester.zhou 已提交
329
## ChargingType
E
esterzhou 已提交
330 331
Enumerates the charging types that can trigger the task.

E
ester.zhou 已提交
332
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
333

E
ester.zhou 已提交
334 335 336 337 338 339
| Name                       | Default Value | Description                  |
| ------------------------- | ---- | -------------------- |
| CHARGING_PLUGGED_ANY      | 0    | Any charging type.|
| CHARGING_PLUGGED_AC       | 1    | DC charging.   |
| CHARGING_PLUGGED_USB      | 2    | USB charging.    |
| CHARGING_PLUGGED_WIRELESS | 3    | Wireless charging.   |
E
esterzhou 已提交
340

E
ester.zhou 已提交
341
## BatteryStatus
E
ester.zhou 已提交
342
Enumerates the battery states that can trigger the task.
E
esterzhou 已提交
343

E
ester.zhou 已提交
344
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
345

E
ester.zhou 已提交
346 347 348 349 350
| Name                        | Default Value | Description                        |
| -------------------------- | ---- | -------------------------- |
| BATTERY_STATUS_LOW         | 0    | A low battery alert is displayed.            |
| BATTERY_STATUS_OKAY        | 1    | The battery level is restored from low to normal.      |
| BATTERY_STATUS_LOW_OR_OKAY | 2    | The battery level is restored from low to normal, or a low battery alert is displayed.|
E
esterzhou 已提交
351

E
ester.zhou 已提交
352
## StorageRequest
E
ester.zhou 已提交
353
Enumerates the storage states that can trigger the task.
E
esterzhou 已提交
354

E
ester.zhou 已提交
355 356
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

E
ester.zhou 已提交
357 358 359 360 361
| Name                       | Default Value | Description                            |
| ------------------------- | ---- | ------------------------------ |
| STORAGE_LEVEL_LOW         | 0    | The storage space is insufficient.              |
| STORAGE_LEVEL_OKAY        | 1    | The storage space is restored from insufficient to normal.        |
| STORAGE_LEVEL_LOW_OR_OKAY | 2    | The storage space is restored from insufficient to normal, or the storage space is insufficient.|