work-scheduler-dev-guide.md 7.0 KB
Newer Older
E
esterzhou 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# Work Scheduler Development

## When to Use

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.


## 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 24 25 26 27 28 29 30 31 32 33
API                                                   |     Description                           
---------------------------------------------------------|-----------------------------------------
function startWork(work: WorkInfo): boolean; | Starts a Work Scheduler task.
function stopWork(work: WorkInfo, needCancel?: boolean): boolean;        | Stops a Work Scheduler task.
function getWorkStatus(workId: number, callback: AsyncCallback<WorkInfo>): void;| Obtains the status of a Work Scheduler task. This method uses an asynchronous callback to return the result.
function getWorkStatus(workId: number): Promise<WorkInfo>; | Obtains the status of a Work Scheduler task. This method uses a promise to return the result.
function obtainAllWorks(callback: AsyncCallback<void>): Array<WorkInfo>;| Obtains Work Scheduler tasks. This method uses an asynchronous callback to return the result.
function obtainAllWorks(): Promise<Array<WorkInfo>>;| Obtains Work Scheduler tasks. This method uses a promise to return the result.
function stopAndClearWorks(): boolean;| Stops and clears Work Scheduler tasks.
function isLastWorkTimeOut(workId: number, callback: AsyncCallback<void>): boolean;| Checks whether the last execution of the specified task has timed out. This method uses an asynchronous callback to return the result. It is applicable to repeated tasks.
function isLastWorkTimeOut(workId: number): Promise<boolean>;| Checks whether the last execution of the specified task has timed out. This method uses a promise to return the result. It is applicable to repeated tasks.
E
esterzhou 已提交
34 35 36 37 38 39 40 41 42

**Table 2** WorkInfo parameters

API|Description|Type                          
---------------------------------------------------------|-----------------------------------------|---------------------------------------------------------
workId | Work ID. Mandatory.|number
bundleName | Name of the Work Scheduler task bundle. Mandatory.|string
abilityName | Name of the component to be notified by a Work Scheduler callback.|string
networkType | Network type.| NetworkType
E
ester.zhou 已提交
43
isCharging | Whether the device is charging.| boolean
E
esterzhou 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
chargerType | Charging type.| ChargingType
batteryLevel | Battery level.| number
batteryStatus| Battery status.|    BatteryStatus
storageRequest|Storage status.|    StorageRequest
isRepeat|Whether the task is repeated.|    boolean
repeatCycleTime |Repeat interval.|    number
repeatCount    |Number of repeat times.| number

**Table 3** Work Scheduler callbacks

API                                                   |     Description                           
---------------------------------------------------------|-----------------------------------------
function onWorkStart(work: WorkInfo): void; | Triggered when the Work Scheduler task starts.
function onWorkStop(work: WorkInfo): void; | Triggered when the Work Scheduler task stops.

### How to Develop

**Implementing WorkSchedulerExtensionAbility**

    import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
E
ester.zhou 已提交
64

E
esterzhou 已提交
65 66 67 68 69 70 71 72 73 74 75 76
    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**

E
ester.zhou 已提交
77 78


E
esterzhou 已提交
79
    import workScheduler from '@ohos.workScheduler';
E
ester.zhou 已提交
80

E
esterzhou 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    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);


**Canceling the Work Scheduler Task**


    import workScheduler from '@ohos.workScheduler';
E
ester.zhou 已提交
98

E
esterzhou 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    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);


**Obtaining a Specified Work Scheduler Task**

1. Callback syntax

    workScheduler.getWorkStatus(50, (err, res) => {
      if (err) {
E
ester.zhou 已提交
118
        console.info('workschedulerLog getWorkStatus failed, because:' + err.code);
E
esterzhou 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
      } 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 已提交
134
      console.info('workschedulerLog getWorkStatus failed, because:' + err.code);
E
esterzhou 已提交
135 136 137 138 139 140 141 142 143
    })


**Obtaining All Work Scheduler Tasks**

1. Callback syntax

    workScheduler.obtainAllWorks((err, res) =>{
      if (err) {
E
ester.zhou 已提交
144
        console.info('workschedulerLog obtainAllWorks failed, because:' + err.code);
E
esterzhou 已提交
145 146 147 148 149 150 151 152 153 154
      } 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 已提交
155
      console.info('workschedulerLog obtainAllWorks failed, because:' + err.code);
E
esterzhou 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168
    })

**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 已提交
169
        console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code);
E
esterzhou 已提交
170 171 172 173 174 175 176 177 178 179 180 181
      } 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 已提交
182
        console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code);
E
esterzhou 已提交
183 184
      });
    })