• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Transient Task (C/C++)
2
3## When to Use
4
5An application is suspended after it runs in the background for a short period of time. If the application needs to execute a short-time task in the background, for example, saving the status, it can request a transient task to extend the running time in the background.
6
7## Available APIs
8
9The following table lists the common APIs. For details, see [API Reference](../reference/apis-backgroundtasks-kit/capi-transient-task-api-h.md#functions).
10
11
12| Name| Description|
13| -------- | -------- |
14| int32_t OH_BackgroundTaskManager_RequestSuspendDelay(const char *reason, TransientTask_Callback callback, TransientTask_DelaySuspendInfo *info); | Requests a transient task.|
15| int32_t OH_BackgroundTaskManager_GetRemainingDelayTime(int32_t requestId, int32_t *delayTime); | Obtains the remaining time of a transient task.|
16| int32_t OH_BackgroundTaskManager_CancelSuspendDelay(int32_t requestId); | Cancels a transient task.|
17| int32_t OH_BackgroundTaskManager_GetTransientTaskInfo(TransientTask_TransientTaskInfo  *transientTaskInfo); | Obtains all information about a transient task, including the remaining quota of the current day.|
18
19## How to Develop
20
21### Encapsulating the Functions and Registering Modules in the napi_init.cpp File
22
231. Encapsulate the functions.
24
25   ```C
26   #include "napi/native_api.h"
27   #include "transient_task/transient_task_api.h"
28
29   TransientTask_DelaySuspendInfo delaySuspendInfo;
30
31   static void callback(void)
32   {
33      // The transient task is about to end. The service cancels the transient task here.
34      OH_BackgroundTaskManager_CancelSuspendDelay(delaySuspendInfo.requestId);
35   }
36
37   // Request a transient task.
38   static napi_value RequestSuspendDelay(napi_env env, napi_callback_info info)
39   {
40         napi_value result;
41         int32_t res = OH_BackgroundTaskManager_RequestSuspendDelay("test", callback, &delaySuspendInfo);
42         if (res == 0) {
43            napi_create_int32(env, delaySuspendInfo.requestId, &result);
44         } else {
45            napi_create_int32(env, -1, &result);
46         }
47         return result;
48   }
49
50   // Obtain the remaining time.
51   static napi_value GetRemainingDelayTime(napi_env env, napi_callback_info info)
52   {
53         napi_value result;
54         int32_t delayTime = 0;
55         int32_t res = OH_BackgroundTaskManager_GetRemainingDelayTime(delaySuspendInfo.requestId, &delayTime);
56         if (res == 0) {
57            napi_create_int32(env, delayTime, &result);
58         } else {
59            napi_create_int32(env, -1, &result);
60         }
61         return result;
62   }
63
64   // Cancel the transient task.
65   static napi_value CancelSuspendDelay(napi_env env, napi_callback_info info)
66   {
67         napi_value result;
68         int32_t res = OH_BackgroundTaskManager_CancelSuspendDelay(delaySuspendInfo.requestId);
69         napi_create_int32(env, res, &result);
70         return result;
71   }
72
73   // Obtain all transient task information.
74   TransientTask_TransientTaskInfo transientTaskInfo;
75
76   static napi_value GetTransientTaskInfo(napi_env env, napi_callback_info info)
77   {
78      napi_value result;
79      napi_create_object(env, &result);
80      int32_t res = OH_BackgroundTaskManager_GetTransientTaskInfo(&transientTaskInfo);
81      napi_value napiRemainingQuota = nullptr;
82      // The data is successfully obtained. The data is formatted and returned to the API.
83      if (res == 0) {
84         napi_create_int32(env, transientTaskInfo.remainingQuota, &napiRemainingQuota);
85         napi_set_named_property(env, result, "remainingQuota", napiRemainingQuota); // Format the total quota of the current day.
86
87         napi_value info {nullptr};
88         napi_create_array(env, &info);
89         uint32_t count = 0;
90         // Format all requested transient task information.
91         for (int index = 0; index < 3; index++) {
92            if (transientTaskInfo.transientTasks[index].requestId == 0) {
93                continue;
94            }
95
96            napi_value napiWork = nullptr;
97            napi_create_object(env, &napiWork);
98
99            napi_value napiRequestId = nullptr;
100            napi_create_int32(env, transientTaskInfo.transientTasks[index].requestId, &napiRequestId);
101            napi_set_named_property(env, napiWork, "requestId", napiRequestId);
102
103            napi_value napiActualDelayTime = nullptr;
104            napi_create_int32(env, transientTaskInfo.transientTasks[index].actualDelayTime, &napiActualDelayTime);
105            napi_set_named_property(env, napiWork, "actualDelayTime", napiActualDelayTime);
106
107            napi_set_element(env, info, count, napiWork);
108            count++;
109         }
110         napi_set_named_property(env, result, "transientTasks", info);
111      } else {
112         napi_create_int32(env, 0, &napiRemainingQuota);
113         napi_set_named_property(env, result, "remainingQuota", napiRemainingQuota);
114         napi_value info {nullptr};
115         napi_create_array(env, &info);
116         napi_set_named_property(env, result, "transientTasks", info);
117      }
118      return result;
119   }
120   ```
121
1222. Register the functions.
123
124   ```C
125   EXTERN_C_START
126   static napi_value Init(napi_env env, napi_value exports)
127   {
128       napi_property_descriptor desc[] = {
129           {"RequestSuspendDelay", nullptr, RequestSuspendDelay, nullptr, nullptr, nullptr, napi_default, nullptr},
130           {"GetRemainingDelayTime", nullptr, GetRemainingDelayTime, nullptr, nullptr, nullptr, napi_default, nullptr},
131           {"CancelSuspendDelay", nullptr, CancelSuspendDelay, nullptr, nullptr, nullptr, napi_default, nullptr},
132           {"GetTransientTaskInfo", nullptr, GetTransientTaskInfo, nullptr, nullptr, nullptr, napi_default, nullptr },
133       };
134       napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
135       return exports;
136   }
137   EXTERN_C_END
138   ```
139
1403. Register the module.
141
142   ```C
143   static napi_module demoModule = {
144       .nm_version = 1,
145       .nm_flags = 0,
146       .nm_filename = nullptr,
147       .nm_register_func = Init,
148       .nm_modname = "entry",
149       .nm_priv = ((void*)0),
150       .reserved = { 0 },
151   };
152
153   extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
154   {
155       napi_module_register(&demoModule);
156   }
157   ```
158
159### Declaring the Functions in the index.d.ts File
160
161   ```ts
162   import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
163
164   export const RequestSuspendDelay: () => number;
165   export const GetRemainingDelayTime: () => number;
166   export const CancelSuspendDelay: () => number;
167   export const GetTransientTaskInfo: () => backgroundTaskManager.TransientTaskInfo;
168   ```
169
170### Calling the Functions in the index.ets File
171
172   ```ts
173   import testTransientTask from 'libentry.so';
174
175   @Entry
176   @Component
177   struct Index {
178     @State message: string = '';
179
180     build() {
181       Row() {
182         Column() {
183           Text(this.message)
184             .fontSize(50)
185             .fontWeight(FontWeight.Bold)
186           Button('Request transient task').onClick(event => {
187             this.RequestSuspendDelay();
188           })
189           Button('Obtain remaining time').onClick(event =>{
190             this.GetRemainingDelayTime();
191           })
192           Button('Cancel transient task').onClick(event =>{
193             this.CancelSuspendDelay();
194           })
195           Button('Obtain all transient task information').onClick(event =>{
196             this.GetTransientTaskInfo();
197           })
198         }
199         .width('100%')
200        }
201       .height('100%')
202     }
203
204     RequestSuspendDelay() {
205       let requestId = testTransientTask.RequestSuspendDelay();
206       console.log("The return requestId is " + requestId);
207     }
208
209     GetRemainingDelayTime() {
210       let time = testTransientTask.GetRemainingDelayTime();
211       console.log("The time is " + time);
212     }
213
214     CancelSuspendDelay() {
215       let ret = testTransientTask.CancelSuspendDelay();
216       console.log("The ret is " + ret);
217     }
218
219     GetTransientTaskInfo() {
220       let ret = testTransientTask.GetTransientTaskInfo();
221       console.log("The ret is " + JSON.stringify(ret));
222     }
223   }
224
225   ```
226
227### Configuring the Library Dependency
228
229Configure the `CMakeLists.txt` file. Add the required shared library, that is, `libtransient_task.so`, to `target_link_libraries` in the `CMakeLists.txt` file automatically generated by the project.
230
231   ```txt
232   target_link_libraries(entry PUBLIC libace_napi.z.so libtransient_task.so)
233   ```
234
235## How to Test
236
2371. Connect to the device and run the program.
238
2392. Touch the `Request transient task` button. The console prints a log. The following is an example:
240
241   ```
242   The return requestId is 1
243   ```
244
2453. Touch the `Obtain remaining time` button. The console prints a log. The following is an example:
246
247   ```
248   The return requestId is 18000
249   ```
2504. Touch the `Cancel transient task` button. The console prints a log. The following is an example:
251
252   ```
253   The ret is 0
254   ```
2555. Touch the `Obtain all transient task information` button. The console prints a log. The following is an example:
256
257   ```
258   The ret is {"remainingQuota":600000,"transientTasks":[]}
259   ```
260> **NOTE**
261>
262>If the `Request transient task` button is touched for more than three consecutive times, an error is reported. For more constraints, see [Transient Task (ArkTS)](transient-task.md#constraints).
263