js-apis-workScheduler.md 13.7 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
esterzhou 已提交
11 12 13 14


## Modules to Import

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

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

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

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

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

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

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

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

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

E
ester.zhou 已提交
40
```js
E
ester.zhou 已提交
41 42 43 44 45 46 47 48 49 50 51 52
  let workInfo = {
      workId: 1,
      batteryLevel:50,
      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
      isRepeat: false,
      isPersisted: true,
      bundleName: "com.example.myapplication",
      abilityName: "MyExtension"
  }
  var res = workScheduler.startWork(workInfo);
  console.info("workschedulerLog res:" + res);
```
E
esterzhou 已提交
53

E
ester.zhou 已提交
54
## workScheduler.stopWork
E
esterzhou 已提交
55 56 57 58
stopWork(work: WorkInfo, needCancel?: boolean): boolean

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

E
ester.zhou 已提交
59
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
60

E
ester.zhou 已提交
61
**Parameters**
E
esterzhou 已提交
62

E
ester.zhou 已提交
63 64 65 66
| Name       | Type                   | Mandatory  | Description        |
| ---------- | --------------------- | ---- | ---------- |
| work       | [WorkInfo](#workinfo) | Yes   | Task to stop. |
| needCancel | boolean               | Yes   | Whether to cancel the task.|
E
esterzhou 已提交
67

E
ester.zhou 已提交
68
**Return value**
E
esterzhou 已提交
69

E
ester.zhou 已提交
70 71 72
| Type     | Description                     |
| ------- | ----------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
E
esterzhou 已提交
73

E
ester.zhou 已提交
74
**Example**
E
esterzhou 已提交
75

E
ester.zhou 已提交
76
```js
E
ester.zhou 已提交
77 78 79 80 81 82 83 84 85 86 87 88
  let workInfo = {
      workId: 1,
      batteryLevel:50,
      batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
      isRepeat: false,
      isPersisted: true,
      bundleName: "com.example.myapplication",
      abilityName: "MyExtension"
     }
  var res = workScheduler.stopWork(workInfo, false);
  console.info("workschedulerLog res:" + res);
```
E
esterzhou 已提交
89

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

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

E
ester.zhou 已提交
95
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
96

E
ester.zhou 已提交
97
**Parameters**
E
esterzhou 已提交
98

E
ester.zhou 已提交
99 100 101 102
| 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 已提交
103

E
ester.zhou 已提交
104
**Example**
E
esterzhou 已提交
105

E
ester.zhou 已提交
106
```js
E
ester.zhou 已提交
107 108
  workScheduler.getWorkStatus(50, (err, res) => {
    if (err) {
E
ester.zhou 已提交
109
      console.info('workschedulerLog getWorkStatus failed, because:' + err.code);
E
ester.zhou 已提交
110 111 112
    } else {
      for (let item in res) {
        console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
E
esterzhou 已提交
113
      }
E
ester.zhou 已提交
114 115 116
    }
  });
```
E
esterzhou 已提交
117 118

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

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

E
ester.zhou 已提交
123
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
124

E
ester.zhou 已提交
125
**Parameters**
E
esterzhou 已提交
126

E
ester.zhou 已提交
127 128 129
| Name   | Type    | Mandatory  | Description      |
| ------ | ------ | ---- | -------- |
| workId | number | Yes   | Task ID.|
E
esterzhou 已提交
130

E
ester.zhou 已提交
131
**Return value**
E
esterzhou 已提交
132

E
ester.zhou 已提交
133 134 135
| 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 已提交
136

E
ester.zhou 已提交
137
**Example**
E
esterzhou 已提交
138

E
ester.zhou 已提交
139
```js
E
ester.zhou 已提交
140 141 142 143 144
  workScheduler.getWorkStatus(50).then((res) => {
    for (let item in res) {
      console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
    }
  }).catch((err) => {
E
ester.zhou 已提交
145
    console.info('workschedulerLog getWorkStatus failed, because:' + err.code);
E
ester.zhou 已提交
146 147
  })
```
E
esterzhou 已提交
148 149

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

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

E
ester.zhou 已提交
154
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
155

E
ester.zhou 已提交
156
**Parameters**
E
esterzhou 已提交
157

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

E
ester.zhou 已提交
162
**Return value**
E
esterzhou 已提交
163

E
ester.zhou 已提交
164 165 166
| Type                           | Description             |
| ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.|
E
esterzhou 已提交
167

E
ester.zhou 已提交
168
**Example**
E
esterzhou 已提交
169

E
ester.zhou 已提交
170
```js
E
ester.zhou 已提交
171 172
  workScheduler.obtainAllWorks((err, res) =>{
    if (err) {
E
ester.zhou 已提交
173
      console.info('workschedulerLog obtainAllWorks failed, because:' + err.code);
E
ester.zhou 已提交
174 175 176 177 178
    } else {
      console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
    }
  });
```
E
esterzhou 已提交
179 180

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

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

E
ester.zhou 已提交
185
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
186

E
ester.zhou 已提交
187
**Return value**
E
esterzhou 已提交
188

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

E
ester.zhou 已提交
193
**Example**
E
esterzhou 已提交
194

E
ester.zhou 已提交
195
```js
E
ester.zhou 已提交
196 197 198
  workScheduler.obtainAllWorks().then((res) => {
    console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
  }).catch((err) => {
E
ester.zhou 已提交
199
    console.info('workschedulerLog obtainAllWorks failed, because:' + err.code);
E
ester.zhou 已提交
200 201
  })
```
E
esterzhou 已提交
202 203 204 205 206 207

## workScheduler.stopAndClearWorks
stopAndClearWorks(): boolean

Stops and cancels all tasks associated with the current application.

E
ester.zhou 已提交
208 209 210
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

**Example**
E
esterzhou 已提交
211

E
ester.zhou 已提交
212
```js
E
ester.zhou 已提交
213 214 215
  let res = workScheduler.stopAndClearWorks();
  console.info("workschedulerLog res:" + res);
```
E
esterzhou 已提交
216 217

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

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

E
ester.zhou 已提交
222
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
223

E
ester.zhou 已提交
224
**Parameters**
E
esterzhou 已提交
225

E
ester.zhou 已提交
226 227 228
| Name     | Type                  | Mandatory  | Description                                      |
| -------- | -------------------- | ---- | ---------------------------------------- |
| workId   | number               | Yes   | Task ID.                                |
E
ester.zhou 已提交
229
| 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 已提交
230

E
ester.zhou 已提交
231
**Return value**
E
esterzhou 已提交
232

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

E
ester.zhou 已提交
237
**Example**
E
esterzhou 已提交
238

E
ester.zhou 已提交
239
```js
E
ester.zhou 已提交
240 241
  workScheduler.isLastWorkTimeOut(500, (err, res) =>{
    if (err) {
E
ester.zhou 已提交
242
      console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code);
E
ester.zhou 已提交
243 244 245 246 247
    } else {
      console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
    }
  });
```
E
esterzhou 已提交
248 249

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

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

E
ester.zhou 已提交
254
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
255

E
ester.zhou 已提交
256
**Parameters**
E
esterzhou 已提交
257

E
ester.zhou 已提交
258 259 260
| Name   | Type    | Mandatory  | Description      |
| ------ | ------ | ---- | -------- |
| workId | number | Yes   | Task ID.|
E
esterzhou 已提交
261

E
ester.zhou 已提交
262
**Return value**
E
esterzhou 已提交
263

E
ester.zhou 已提交
264 265 266
| 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 已提交
267

E
ester.zhou 已提交
268
**Example**
E
esterzhou 已提交
269

E
ester.zhou 已提交
270
```js
E
ester.zhou 已提交
271 272 273
  workScheduler.isLastWorkTimeOut(500)
    .then(res => {
      console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
E
esterzhou 已提交
274
    })
E
ester.zhou 已提交
275
    .catch(err =>  {
E
ester.zhou 已提交
276
      console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code);
E
ester.zhou 已提交
277 278
    });
```
E
esterzhou 已提交
279

E
ester.zhou 已提交
280
## WorkInfo
E
ester.zhou 已提交
281
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 已提交
282

E
ester.zhou 已提交
283 284
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler

E
ester.zhou 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
| 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.          |
E
ester.zhou 已提交
302 303

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

E
ester.zhou 已提交
306
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
307

E
ester.zhou 已提交
308 309 310 311 312 313 314 315
| 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 已提交
316

E
ester.zhou 已提交
317
## ChargingType
E
esterzhou 已提交
318 319
Enumerates the charging types that can trigger the task.

E
ester.zhou 已提交
320
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
E
esterzhou 已提交
321

E
ester.zhou 已提交
322 323 324 325 326 327
| 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 已提交
328

E
ester.zhou 已提交
329
## BatteryStatus
E
ester.zhou 已提交
330
Enumerates the battery states that can trigger the task.
E
esterzhou 已提交
331

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

E
ester.zhou 已提交
334 335 336 337 338
| 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 已提交
339

E
ester.zhou 已提交
340
## StorageRequest
E
ester.zhou 已提交
341
Enumerates the storage states that can trigger the task.
E
esterzhou 已提交
342

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

E
ester.zhou 已提交
345 346 347 348 349
| 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.|