• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# WorkSchedulerExtensionAbility Development
2
3If your application needs to execute a non-real-time task or a persistent task, you can harness the Work Scheduler mechanism, which will schedule the task when the preset conditions (including the network type, charging type, storage status, battery status, and timing status) are met.
4
5**WorkSchedulerExtensionAbility** provides callbacks for Work Scheduler tasks. When a Work Scheduler task starts or stops, these callbacks are invoked to process your service logic.
6
7## Working Principles
8
9Figure 1 shows the working principle of Work Scheduler.
10
11**Figure 1** Work Scheduler working principle
12
13![WorkSchedulerExtensionAbility](figures/WorkSchedulerExtensionAbility.png)
14
15An application registers, cancels, and queries Work Scheduler tasks through the [workScheduler APIs](../reference/apis/js-apis-resourceschedule-workScheduler.md). It starts and stops Work Scheduler tasks through the [WorkSchedulerExtensionAbility APIs](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md).
16
17The application service layer detects and determines the conditions. If the preset conditions are met, the application service layer calls back the **WorkSchedulerExtensionAbility** object to start the application and triggers the **onWorkStart** and **onWorkStop** callbacks.
18
19## Available APIs
20
21The **WorkSchedulerExtensionAbility** class has the following APIs. For details, see [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md).
22
23| Name| Description|
24| -------- | -------- |
25| onWorkStart(work: workScheduler.WorkInfo): void | Called when the Work Scheduler task starts.|
26| onWorkStop(work: workScheduler.WorkInfo): void | Called when the Work Scheduler task stops.|
27
28## How to Develop
29
30To create a WorkScheduler project in DevEco Studio, perform the following steps:
31
32- [Implement callbacks for Work Scheduler](#implementing-callbacks-for-work-scheduler): Develop the callbacks provided by **WorkSchedulerExtensionAbility**.
33
34- [Implement Work Scheduler](#implementing-work-scheduler): Develop the [workScheduler APIs] to implement functions such as starting or stopping Work Scheduler tasks.
35
36- [Set the configuration file](#setting-the-configuration-file): Set the configuration file **module.json5**.
37
38### Implementing Callbacks for Work Scheduler
39
401. Create a module named **library** in the root directory of the project, with the **Ohos Library** template selected.
41
422. In the **./library/src/main/ets** directory under **library**, create an ArkTS file named **workAbility.ets** and implement the callbacks for Work Scheduler.
43
44    Import the module.
45
46    ```ts
47    import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
48    ```
49
50    Implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
51
52    ```ts
53    export default class workAbility extends WorkSchedulerExtensionAbility {
54      // Callback invoked when the Work Scheduler task starts.
55      onWorkStart(workInfo) {
56        console.log(`onWorkStart CommonEvent publish start ${JSON.stringify(workInfo)}`);
57        // Publish an upgrade notification.
58        let notificationRequest = notification.getNotificationContentBasic('upgrade', upgradeMessage, '');
59        notification.publish(notificationRequest, (err) => {
60          if (err) {
61            console.log(`onWorkStart notification publish err ${JSON.stringify(err)}`);
62          }
63          console.log(`onWorkStart notification publish success`);
64        });
65      }
66
67      // Callback invoked when the Work Scheduler task stops.
68      onWorkStop(workInfo) {
69        // Publish an upgrade completion notification.
70        let notificationRequest = notification.getNotificationContentBasic('upgrade', 'upgrade success', '');
71        notification.publish(notificationRequest, (err) => {
72          if (err) {
73            console.log(`onWorkStop notification publish err ${JSON.stringify(err)}`);
74          }
75          console.log(`onWorkStop notification publish success`);
76        });
77      }
78    }
79    ```
80
813. In the **./entry/src/main/ets** directory under the **entry** module of the project, create a directory named **workAbility**. In the **workAbility** directory, create an ArkTS file named **WorkTest.ets** and implement the callbacks for Work Scheduler.
82
83    Import the module.
84
85        ```ts
86        import { workAbility } from '@ohos/library';
87        ```
88
89    Inherit from **workAbility** and implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
90
91        ```ts
92        export default class WorkTest extends workAbility {
93          onWorkStart(workInfo) {
94            console.log(`onWorkStartTest start ${JSON.stringify(workInfo)}`);
95            super.onWorkStart(workInfo);
96          }
97
98          onWorkStopTest(workInfo) {
99            super.onWorkStop(workInfo);
100            console.log(`onWorkStop value`);
101          }
102        }
103        ```
104
105### Implementing Work Scheduler
106
1071. In the **./library/src/main/ets** directory under **library**, create a TypeScript file named **DelayWork.ts**, and implement the Work Scheduler APIs.
108
109    Import the module.
110
111    ```ts
112    import workScheduler from '@ohos.resourceschedule.workScheduler';
113    ```
114
115    Encapsulate the APIs for starting and stopping Work Scheduler tasks.
116
117    ```ts
118    export default class DelayWork {
119      private workInfo = {
120        workId: 1,
121        networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
122        bundleName: '',
123        abilityName: ''
124      }
125      // Start the Work Scheduler task.
126      startWork(bundleName: string, abilityName: string) {
127        this.workInfo.bundleName = bundleName;
128        this.workInfo.abilityName = abilityName;
129        try {
130          workScheduler.startWork(this.workInfo);
131          console.log(`startWork success`);
132        } catch (error) {
133          Logger.error(TAG, `startWork startwork failed. code is ${error.code} message is ${error.message}`);
134          prompt.showToast({
135            message: `${error.message}`
136          })
137        }
138      }
139
140      // Stop the Work Scheduler task.
141      stopWork(bundleName: string, abilityName: string) {
142        this.workInfo.bundleName = bundleName;
143        this.workInfo.abilityName = abilityName;
144        workScheduler.stopWork(this.workInfo, false);
145        console.log(`stopWork`);
146      }
147    }
148    ```
149
1502. In the **./entry/src/main/ets/pages/index.ets** directory under the **entry** module of the project, add the **Upgrade** button, which, when being clicked, will call the API encapsulated in **library** to start the Work Scheduler task.
151
152    Import the module.
153
154    ```ts
155    import { workAbility } from '@ohos/library';
156    ```
157
158    Add the **Upgrade** button, which, when being clicked, will call the API encapsulated in **library** to start the Work Scheduler task. In the API, **bundleName** and **abilityName** are passed in, where the value of **abilityName** is **WorkTest**.
159
160    ```ts
161    Button($r('app.string.upgrade'))
162      .width('60%')
163      .height(40)
164      .fontSize(30)
165      .onClick(() => {
166        this.work.startWork('ohos.samples.workscheduler', 'WorkTest');
167      })
168    ```
169
170    When the component is destructed, it calls the API to stop the Work Scheduler task.
171
172    ```ts
173    aboutToDisappear() {
174      this.work.stopWork('ohos.samples.workscheduler', 'WorkTest');
175    }
176    ```
177
178### Setting the Configuration File
179
1801. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) under the **entry** module. Set **type** to **workScheduler** and **srcEnty** to the code path of the WorkSchedulerExtensionAbility component.
181
182     ```json
183     {
184       "module": {
185           "extensionAbilities": [
186             {
187               "name": "WorkTest",
188               "srcEnty": "./ets/workAbility/WorkTest.ets",
189               "label": "$string:WorkSchedulerExtensionAbility_label",
190               "description": "$string:WorkSchedulerExtensionAbility_desc",
191               "type": "workScheduler"
192             }
193           ]
194       }
195     }
196     ```