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

## When to Use

E
ester.zhou 已提交
5
If your application needs to execute a non-real-time 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 constraints on the Work Scheduler usage, see [Work Scheduler Overview](./work-scheduler-overview.md).
E
esterzhou 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22


## Available APIs
Import the **workScheduler** package to implement registration:
```js
import workScheduler from '@ohos.workScheduler';
```

Import the **WorkSchedulerExtensionAbility** package to implement callback:
```js
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```

### Work Scheduler

**Table 1** Major workScheduler APIs

E
ester.zhou 已提交
23
 API                                                          | Description                                                  
E
ester.zhou 已提交
24
 ------------------------------------------------------------ | ------------------------------------------------------------ 
E
ester.zhou 已提交
25 26 27 28 29 30
 startWork(work: WorkInfo): boolean                           | Starts a Work Scheduler task.                                
 stopWork(work: WorkInfo, needCancel?: boolean): boolean      | 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. 
E
ester.zhou 已提交
31
 stopAndClearWorks(): boolean;                                | Stops and clears Work Scheduler tasks.                       
E
ester.zhou 已提交
32 33
 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 已提交
34 35 36

**Table 2** WorkInfo parameters

E
ester.zhou 已提交
37 38
> **NOTE**
>
E
ester.zhou 已提交
39
> For details about the constraints on configuring **WorkInfo**, see [Work Scheduler Overview](./work-scheduler-overview.md).
E
ester.zhou 已提交
40

E
ester.zhou 已提交
41
Name| Type|Description                      
E
esterzhou 已提交
42
---------------------------------------------------------|-----------------------------------------|---------------------------------------------------------
E
ester.zhou 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55
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.
networkType  | [NetworkType](../reference/apis/js-apis-workScheduler.md#networktype) | Network type.
isCharging| boolean | Whether the device is charging.
chargerType| [ChargingType](../reference/apis/js-apis-workScheduler.md#chargingtype) | Charging type.
batteryLevel| number | Battery level.
batteryStatus| [BatteryStatus](../reference/apis/js-apis-workScheduler.md#batterystatus) | Battery status.
storageRequest| [StorageRequest](../reference/apis/js-apis-workScheduler.md#storagerequest) |Storage status.
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 已提交
56 57 58

**Table 3** Work Scheduler callbacks

E
ester.zhou 已提交
59 60 61 62
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 已提交
63 64 65 66 67 68

### How to Develop

**Implementing WorkSchedulerExtensionAbility**

    import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
E
ester.zhou 已提交
69
    
E
esterzhou 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82
    export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
        onWorkStart(workInfo) {
            console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
        }
        onWorkStop(workInfo) {
            console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
        }
    }


**Registering a Work Scheduler Task**

    import workScheduler from '@ohos.workScheduler';
E
ester.zhou 已提交
83
    
E
esterzhou 已提交
84 85 86 87 88 89
    let workInfo = {
        workId: 1,
        batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
        isRepeat: false,
        isPersisted: true,
        bundleName: "com.example.myapplication",
E
ester.zhou 已提交
90 91 92 93 94 95 96
        abilityName: "MyExtension",
        parameters: {
          mykey0: 1,
          mykey1: "string value",
          mykey2: true,
          mykey3: 1.5
      }
E
esterzhou 已提交
97 98 99 100 101 102 103 104 105
    }
    var res = workScheduler.startWork(workInfo);
    console.info("workschedulerLog res:" + res);


**Canceling the Work Scheduler Task**


    import workScheduler from '@ohos.workScheduler';
E
ester.zhou 已提交
106
    
E
esterzhou 已提交
107 108 109 110 111 112
    let workInfo = {
        workId: 1,
        batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
        isRepeat: false,
        isPersisted: true,
        bundleName: "com.example.myapplication",
E
ester.zhou 已提交
113 114 115 116 117 118 119
        abilityName: "MyExtension",
        parameters: {
          mykey0: 1,
          mykey1: "string value",
          mykey2: true,
          mykey3: 1.5
      }
E
esterzhou 已提交
120 121 122 123 124 125 126 127 128 129 130
    }
    var res = workScheduler.stopWork(workInfo, false);
    console.info("workschedulerLog res:" + res);


**Obtaining a Specified Work Scheduler Task**

1. Callback syntax

    workScheduler.getWorkStatus(50, (err, res) => {
      if (err) {
E
ester.zhou 已提交
131
        console.info('workschedulerLog getWorkStatus failed, because:' + err.code);
E
esterzhou 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
      } else {
        for (let item in res) {
          console.info('workschedulerLog getWorkStatuscallback success,' + item + ' is:' + res[item]);
        }
      }
    });


2. Promise syntax

    workScheduler.getWorkStatus(50).then((res) => {
      for (let item in res) {
        console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
      }
    }).catch((err) => {
E
ester.zhou 已提交
147
      console.info('workschedulerLog getWorkStatus failed, because:' + err.code);
E
esterzhou 已提交
148 149 150 151 152 153 154 155 156
    })


**Obtaining All Work Scheduler Tasks**

1. Callback syntax

    workScheduler.obtainAllWorks((err, res) =>{
      if (err) {
E
ester.zhou 已提交
157
        console.info('workschedulerLog obtainAllWorks failed, because:' + err.code);
E
esterzhou 已提交
158 159 160 161 162 163 164 165 166 167
      } else {
        console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
      }
    });

2. Promise syntax

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

**Stopping and Clearing Work Scheduler Tasks**

    let res = workScheduler.stopAndClearWorks();
    console.info("workschedulerLog res:" + res);

**Checking Whether the Last Execution Has Timed Out**

1. Callback syntax

    workScheduler.isLastWorkTimeOut(500, (err, res) =>{
      if (err) {
E
ester.zhou 已提交
182
        console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code);
E
esterzhou 已提交
183 184 185 186 187 188 189 190 191 192 193 194
      } else {
        console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
      }
    });

2. Promise syntax

    workScheduler.isLastWorkTimeOut(500)
      .then(res => {
        console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
      })
      .catch(err =>  {
E
ester.zhou 已提交
195
        console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code);
E
esterzhou 已提交
196 197
      });
    })