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

## When to Use

G
Gloria 已提交
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. Your application must implement the callbacks provided by [WorkSchedulerExtensionAbility](./workscheduler-extensionability.md) for Work Scheduler tasks. 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
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.
G
Gloria 已提交
17 18 19
obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo>;| Obtains all the Work Scheduler tasks. This API uses an asynchronous callback to return the result.
obtainAllWorks(): Promise<Array\<WorkInfo>>;| Obtains all the Work Scheduler tasks. This API uses a promise to return the result.
stopAndClearWorks(): void;| Stops and clears all the Work Scheduler tasks.
20 21
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

G
Gloria 已提交
25
For details about the restriction 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
---------------------------------------------------------|-----------------------------------------|---------------------------------------------------------
G
Gloria 已提交
29 30 31
workId| number | ID of the Work Scheduler task. Mandatory.
bundleName| string | Bundle name of the Work Scheduler task. Mandatory.
abilityName| string | Name of the ability 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

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

### How to Develop

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

G
Gloria 已提交
54 55 56 57 58
   Import the **workScheduler** module.
   
   ```js
   import workScheduler from '@ohos.resourceschedule.workScheduler';
   ```
59

G
Gloria 已提交
60 61 62 63
   Import the **WorkSchedulerExtensionAbility** module.
   ```js
   import WorkSchedulerExtensionAbility from    '@ohos.WorkSchedulerExtensionAbility';
   ```
E
esterzhou 已提交
64

G
Gloria 已提交
65
2. Develop an ExtensionAbility to execute a Work Scheduler task. For details about the ExtensionAbility, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md) and [WorkSchedulerExtensionAbility Development](./workscheduler-extensionability.md).
E
esterzhou 已提交
66

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

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


G
Gloria 已提交
81
3. Start a Work Scheduler task.
E
esterzhou 已提交
82

83 84
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
E
ester.zhou 已提交
85
    
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
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 已提交
107 108


G
Gloria 已提交
109
4. Stop the Work Scheduler task.
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

```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 已提交
135 136


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

139 140 141 142 143 144
```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 已提交
145
      for (let item in res) {
146
        console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
E
esterzhou 已提交
147
      }
148 149 150 151 152 153
    }
  });
} catch (error) {
  console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
}
```
E
esterzhou 已提交
154 155


G
Gloria 已提交
156
6. Obtain all the Work Scheduler tasks.
E
esterzhou 已提交
157

158 159 160 161 162 163 164 165 166 167 168 169 170
```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 已提交
171

G
Gloria 已提交
172
7. Stop and clear all the Work Scheduler tasks.
E
esterzhou 已提交
173

174 175 176 177 178 179 180 181
```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 已提交
182

G
Gloria 已提交
183
8. Check whether the last execution of a specified Work Scheduler task has timed out.
E
esterzhou 已提交
184

185 186 187 188 189 190 191 192 193 194 195 196 197
```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 已提交
198