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

## When to Use

5 6
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 已提交
7 8 9 10 11

## Available APIs

**Table 1** Major workScheduler APIs

12 13 14 15 16 17
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 已提交
18 19 20
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.
21 22
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 已提交
23 24 25

**Table 2** WorkInfo parameters

G
Gloria 已提交
26
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 已提交
27

E
ester.zhou 已提交
28
Name| Type|Description                      
E
esterzhou 已提交
29
---------------------------------------------------------|-----------------------------------------|---------------------------------------------------------
G
Gloria 已提交
30 31 32
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.
33
networkType  | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.
E
ester.zhou 已提交
34
isCharging| boolean | Whether the device is charging.
35
chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.
E
ester.zhou 已提交
36
batteryLevel| number | Battery level.
37 38
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 已提交
39 40 41
isRepeat| boolean |Whether the task is repeated.
repeatCycleTime| number |Repeat interval.
repeatCount | number|Number of repeat times.
42
parameters | {[key: string]: number | string | boolean} |Carried parameters.
E
esterzhou 已提交
43 44 45

**Table 3** Work Scheduler callbacks

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

### How to Develop

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

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

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

G
Gloria 已提交
66
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 已提交
67

68 69 70 71 72 73 74 75 76 77 78 79
   ```ts
   import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';

   export default class MyExtension extends WorkSchedulerExtensionAbility {
       onWorkStart(workInfo) {
           console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
       }
       onWorkStop(workInfo) {
           console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
       }
   }
   ```
E
esterzhou 已提交
80 81


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

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


G
Gloria 已提交
110
4. Stop the Work Scheduler task.
111

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
   ```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 已提交
137 138


139
5. Obtain a specified Work Scheduler task.
E
esterzhou 已提交
140

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

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

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

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

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

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

186 187 188 189 190 191 192 193 194 195 196 197 198
   ```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}`);
   }
   ```