work-scheduler-dev-guide.md 7.7 KB
Newer Older
E
esterzhou 已提交
1 2 3 4
# Work Scheduler Development

## When to Use

5
If your application needs to execute a non-real-time task or a persistent task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
E
esterzhou 已提交
6 7 8 9 10

## Available APIs

**Table 1** Major workScheduler APIs

11 12 13 14 15 16 17 18 19 20 21
API                                                   |     Description                           
---------------------------------------------------------|-----------------------------------------
startWork(work: WorkInfo): void; | Starts a Work Scheduler task.
stopWork(work: WorkInfo, needCancel?: boolean): void;        | Stops a Work Scheduler task.
getWorkStatus(workId: number, callback: AsyncCallback\<WorkInfo>): void;| Obtains the status of a Work Scheduler task. This API uses an asynchronous callback to return the result.
getWorkStatus(workId: number): Promise\<WorkInfo>; | Obtains the status of a Work Scheduler task. This API uses a promise to return the result.
obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo>;| Obtains Work Scheduler tasks. This API uses an asynchronous callback to return the result.
obtainAllWorks(): Promise<Array\<WorkInfo>>;| Obtains Work Scheduler tasks. This API uses a promise to return the result.
stopAndClearWorks(): void;| Stops and clears Work Scheduler tasks.
isLastWorkTimeOut(workId: number, callback: AsyncCallback\<void>): boolean;| Checks whether the last execution of the specified task has timed out. This API uses an asynchronous callback to return the result. It is applicable to repeated tasks.
isLastWorkTimeOut(workId: number): Promise\<boolean>;| Checks whether the last execution of the specified task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks.
E
esterzhou 已提交
22 23 24

**Table 2** WorkInfo parameters

25
For details about the constraints on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
E
ester.zhou 已提交
26

E
ester.zhou 已提交
27
Name| Type|Description                      
E
esterzhou 已提交
28
---------------------------------------------------------|-----------------------------------------|---------------------------------------------------------
E
ester.zhou 已提交
29 30 31
workId| number | Work ID. Mandatory.
bundleName| string | Name of the Work Scheduler task bundle. Mandatory.
abilityName| string | Name of the component to be notified by a Work Scheduler callback. Mandatory.
32
networkType  | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.
E
ester.zhou 已提交
33
isCharging| boolean | Whether the device is charging.
34
chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.
E
ester.zhou 已提交
35
batteryLevel| number | Battery level.
36 37
batteryStatus| [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.
storageRequest| [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) |Storage status.
E
ester.zhou 已提交
38 39 40 41
isRepeat| boolean |Whether the task is repeated.
repeatCycleTime| number |Repeat interval.
repeatCount | number|Number of repeat times.
parameters | {[key: string]: any} |Carried parameters.
E
esterzhou 已提交
42 43 44

**Table 3** Work Scheduler callbacks

E
ester.zhou 已提交
45 46 47 48
Name                                                   |     Description                           
---------------------------------------------------------|-----------------------------------------
onWorkStart(work: WorkInfo): void | Triggered when the Work Scheduler task starts.
onWorkStop(work: WorkInfo): void | Triggered when the Work Scheduler task stops.
E
esterzhou 已提交
49 50 51

### How to Develop

52
1. Import the modules.
E
esterzhou 已提交
53

54 55 56 57 58 59 60 61 62
   Import the **workScheduler** package to implement registration:
```js
import workScheduler from '@ohos.resourceschedule.workScheduler';
```

   Import the **WorkSchedulerExtensionAbility** package to implement callback:
```js
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```
E
esterzhou 已提交
63

64
2. Develop an Extension ability to execute a Work Scheduler task. For details about the Extension ability, see [ExtensionAbility Mechanism](../ability/stage-brief.md#extensionability-mechanism).
E
esterzhou 已提交
65

66 67
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
E
esterzhou 已提交
68

69 70 71
export default class MyExtension extends WorkSchedulerExtensionAbility {
    onWorkStart(workInfo) {
        console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
E
esterzhou 已提交
72
    }
73 74 75 76 77
    onWorkStop(workInfo) {
        console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
    }
}
```
E
esterzhou 已提交
78 79


80
3. Register a Work Scheduler task.
E
esterzhou 已提交
81

82 83
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
E
ester.zhou 已提交
84
    
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
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}`);
}
```
E
esterzhou 已提交
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
4. Cancel the Work Scheduler task.

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

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}`);
}
```
E
esterzhou 已提交
134 135


136
5. Obtain a specified Work Scheduler task.
E
esterzhou 已提交
137

138 139 140 141 142 143
```ts
try{
  workScheduler.getWorkStatus(50, (error, res) => {
    if (error) {
      console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
    } else {
E
esterzhou 已提交
144
      for (let item in res) {
145
        console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
E
esterzhou 已提交
146
      }
147 148 149 150 151 152
    }
  });
} catch (error) {
  console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
}
```
E
esterzhou 已提交
153 154


155
6. Obtain all Work Scheduler tasks.
E
esterzhou 已提交
156

157 158 159 160 161 162 163 164 165 166 167 168 169
```ts
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}`);
}
```
E
esterzhou 已提交
170

171
7. Stop and clear Work Scheduler tasks.
E
esterzhou 已提交
172

173 174 175 176 177 178 179 180
```ts
try{
  workScheduler.stopAndClearWorks();
  console.info(`workschedulerLog stopAndClearWorks success`);
} catch (error) {
  console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`);
}
```
E
esterzhou 已提交
181

182
8. Check whether the last execution has timed out.
E
esterzhou 已提交
183

184 185 186 187 188 189 190 191 192 193 194 195 196
```ts
try{
  workScheduler.isLastWorkTimeOut(500, (error, res) =>{
    if (error) {
      onsole.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}`);
}
```
E
esterzhou 已提交
197