• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Work Scheduler Development
2
3## When to Use
4
5If 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.
6For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
7
8## Available APIs
9
10**Table 1** Major workScheduler APIs
11
12API                                                   |     Description
13---------------------------------------------------------|-----------------------------------------
14startWork(work: WorkInfo): void; | Starts a Work Scheduler task.
15stopWork(work: WorkInfo, needCancel?: boolean): void;        | Stops a Work Scheduler task.
16getWorkStatus(workId: number, callback: AsyncCallback\<WorkInfo>): void;| Obtains the status of a Work Scheduler task. This API uses an asynchronous callback to return the result.
17getWorkStatus(workId: number): Promise\<WorkInfo>; | Obtains the status of a Work Scheduler task. This API uses a promise to return the result.
18obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo>;| Obtains all the Work Scheduler tasks. This API uses an asynchronous callback to return the result.
19obtainAllWorks(): Promise<Array\<WorkInfo>>;| Obtains all the Work Scheduler tasks. This API uses a promise to return the result.
20stopAndClearWorks(): void;| Stops and clears all the Work Scheduler tasks.
21isLastWorkTimeOut(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.
22isLastWorkTimeOut(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.
23
24**Table 2** WorkInfo parameters
25
26For details about the restriction on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
27
28Name| Type|Description
29---------------------------------------------------------|-----------------------------------------|---------------------------------------------------------
30workId| number | ID of the Work Scheduler task. Mandatory.
31bundleName| string | Bundle name of the Work Scheduler task. Mandatory.
32abilityName| string | Name of the ability to be notified by a Work Scheduler callback. Mandatory.
33networkType  | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.
34isCharging| boolean | Whether the device is charging.
35chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.
36batteryLevel| number | Battery level.
37batteryStatus| [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.
38storageRequest| [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) |Storage status.
39isRepeat| boolean |Whether the task is repeated.
40repeatCycleTime| number |Repeat interval.
41repeatCount | number|Number of repeat times.
42parameters | {[key: string]: number | string | boolean} |Carried parameters.
43
44**Table 3** Work Scheduler callbacks
45
46API                                                   |     Description
47---------------------------------------------------------|-----------------------------------------
48onWorkStart(work: WorkInfo): void | Called when the Work Scheduler task starts.
49onWorkStop(work: WorkInfo): void | Called when the Work Scheduler task stops.
50
51### How to Develop
52
531. Import the modules.
54
55   Import the **workScheduler** module.
56
57   ```js
58   import workScheduler from '@ohos.resourceschedule.workScheduler';
59   ```
60
61   Import the **WorkSchedulerExtensionAbility** module.
62   ```js
63   import WorkSchedulerExtensionAbility from    '@ohos.WorkSchedulerExtensionAbility';
64   ```
65
662. 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).
67
68   ```ts
69   import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
70
71   export default class MyExtension extends WorkSchedulerExtensionAbility {
72       onWorkStart(workInfo) {
73           console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
74       }
75       onWorkStop(workInfo) {
76           console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
77       }
78   }
79   ```
80
81
823. Start a Work Scheduler task.
83
84   ```ts
85   import workScheduler from '@ohos.resourceschedule.workScheduler';
86
87   let workInfo = {
88       workId: 1,
89       batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
90       isRepeat: false,
91       isPersisted: true,
92       bundleName: "com.example.myapplication",
93       abilityName: "MyExtension",
94       parameters: {
95         mykey0: 1,
96         mykey1: "string value",
97         mykey2: true,
98         mykey3: 1.5
99     }
100   }
101   try{
102     workScheduler.startWork(workInfo);
103     console.info('workschedulerLog startWork success');
104   } catch (error) {
105     console.error(`workschedulerLog startwork failed. code is       ${error.code} message is ${error.message}`);
106   }
107   ```
108
109
1104. Stop the Work Scheduler task.
111
112   ```ts
113   import workScheduler from '@ohos.resourceschedule.workScheduler';
114
115   let workInfo = {
116       workId: 1,
117       batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
118       isRepeat: false,
119       isPersisted: true,
120       bundleName: "com.example.myapplication",
121       abilityName: "MyExtension",
122       parameters: {
123         mykey0: 1,
124         mykey1: "string value",
125         mykey2: true,
126         mykey3: 1.5
127       }
128   }
129   try{
130       workScheduler.stopWork(workInfo, false);
131       console.info('workschedulerLog stopWork success');
132   } catch (error) {
133       console.error(`workschedulerLog stopWork failed. code is    ${error.code} message is ${error.message}`);
134   }
135
136   ```
137
138
1395. Obtain a specified Work Scheduler task.
140
141   ```ts
142   try{
143     workScheduler.getWorkStatus(50, (error, res) => {
144       if (error) {
145         console.error(`workschedulerLog getWorkStatus failed. code is    ${error.code} message is ${error.message}`);
146       } else {
147         for (let item in res) {
148           console.info(`workschedulerLog getWorkStatus success, ${item}    is: ${res[item]}`);
149         }
150       }
151     });
152   } catch (error) {
153     console.error(`workschedulerLog getWorkStatus failed. code is    ${error.code} message is ${error.message}`);
154   }
155   ```
156
1576. Obtain all the Work Scheduler tasks.
158
159   ```ts
160   try{
161     workScheduler.obtainAllWorks((error, res) =>{
162       if (error) {
163         console.error(`workschedulerLog obtainAllWorks failed. code is    ${error.code} message is ${error.message}`);
164       } else {
165         console.info(`workschedulerLog obtainAllWorks success, data is:    ${JSON.stringify(res)}`);
166       }
167     });
168   } catch (error) {
169     console.error(`workschedulerLog obtainAllWorks failed. code is    ${error.code} message is ${error.message}`);
170   }
171   ```
172
1737. Stop and clear all the Work Scheduler tasks.
174
175   ```ts
176   try{
177     workScheduler.stopAndClearWorks();
178     console.info(`workschedulerLog stopAndClearWorks success`);
179   } catch (error) {
180     console.error(`workschedulerLog stopAndClearWorks failed. code is    ${error.code} message is ${error.message}`);
181   }
182   ```
183
1848. Check whether the last execution of a specified Work Scheduler task has timed out.
185
186   ```ts
187   try{
188     workScheduler.isLastWorkTimeOut(500, (error, res) =>{
189       if (error) {
190         onsole.error(`workschedulerLog isLastWorkTimeOut failed. code   is ${error.code} message is ${error.message}`);
191       } else {
192         console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
193       }
194     });
195   } catch (error) {
196     console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
197   }
198   ```
199