1# @ohos.taskpool (Starting the Task Pool)
2
3The task pool provides a multi-thread running environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. You can use the **TaskPool** APIs to create background tasks and perform operations on them, for example, executing or canceling a task. Theoretically, you can create an unlimited number of tasks, but this is not recommended for memory considerations. In addition, you are not advised performing blocking operations in a task, especially indefinite blocking. Long-time blocking operations occupy worker threads and may block other task scheduling, adversely affecting your application performance.
4
5You can determine the execution sequence of tasks with the same priority. They are executed in the same sequence as you call the task execution APIs. The default task priority is **MEDIUM**.
6
7If the number of tasks to be executed is greater than the number of worker threads in the task pool, the task pool scales out based on load balancing to minimize the waiting duration. Similarly, when the number of tasks to be executed falls below the number of worker threads, the task pool scales in to reduce the number of worker threads.
8
9The **TaskPool** APIs return error codes in numeric format. For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
10
11For details about the precautions for using **TaskPool**, see [Precautions for TaskPool](../../arkts-utils/taskpool-introduction.md#precautions-for-taskpool).
12
13> **NOTE**
14>
15> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
16
17## Modules to Import
18
19```ts
20import { taskpool } from '@kit.ArkTS';
21```
22## taskpool.execute
23
24execute(func: Function, ...args: Object[]): Promise\<Object>
25
26Places a function to be executed in the internal queue of the task pool. The function is not executed immediately. It waits to be distributed to the worker thread for execution. In this mode, the function cannot be canceled.
27
28**System capability**: SystemCapability.Utils.Lang
29
30**Atomic service API**: This API can be used in atomic services since API version 11.
31
32**Parameters**
33
34| Name| Type     | Mandatory| Description                                                                  |
35| ------ | --------- | ---- | ---------------------------------------------------------------------- |
36| func   | Function  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
37| args   | Object[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
38
39**Return value**
40
41| Type             | Description                                |
42| ----------------- | ------------------------------------ |
43| Promise\<Object>  | Promise used to return an object that carries the function execution result.|
44
45**Error codes**
46
47For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
48
49| ID| Error Message                                     |
50| -------- | -------------------------------------------- |
51| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
52| 10200006 | An exception occurred during serialization.  |
53| 10200014 | The function is not marked as concurrent.      |
54
55**Example**
56
57```ts
58@Concurrent
59function printArgs(args: number): number {
60    console.info("printArgs: " + args);
61    return args;
62}
63
64taskpool.execute(printArgs, 100).then((value: Object) => { // 100: test number
65  console.info("taskpool result: " + value);
66});
67```
68
69
70## taskpool.execute<sup>13+</sup>
71
72execute<A extends Array\<Object>, R>(func: (...args: A) => R | Promise\<R>, ...args: A): Promise\<R>
73
74Verifies the passed-in parameter types and return value type of a concurrent function, and places the function to execute in the internal queue of the task pool.
75
76**System capability**: SystemCapability.Utils.Lang
77
78**Atomic service API**: This API can be used in atomic services since API version 13.
79
80**Parameters**
81
82| Name| Type     | Mandatory| Description                                                                  |
83| ------ | --------- | ---- | ---------------------------------------------------------------------- |
84| func   | (...args: A) => R \| Promise\<R>  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
85| args   | A | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
86
87**Return value**
88
89| Type             | Description                                |
90| ----------------- | ------------------------------------ |
91| Promise\<R>  | Promise used to return an object that carries the function execution result.|
92
93**Error codes**
94
95For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
96
97| ID| Error Message                                     |
98| -------- | -------------------------------------------- |
99| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
100| 10200006 | An exception occurred during serialization.  |
101| 10200014 | The function is not marked as concurrent.      |
102
103**Example**
104
105```ts
106@Concurrent
107function printArgs(args: number): number {
108    console.info("printArgs: " + args);
109    return args;
110}
111
112@Concurrent
113function testWithThreeParams(a: number, b: string, c: number): string {
114  return b;
115}
116
117@Concurrent
118function testWithArray(args: [number, string]): string {
119  return "success";
120}
121
122taskpool.execute<[number], number>(printArgs, 100).then((value: number) => { // 100: test number
123  console.info("taskpool result: " + value);
124});
125
126taskpool.execute<[number, string, number], string>(testWithThreeParams, 100, "test", 100).then((value: string) => {})
127
128taskpool.execute<[[number, string]], string>(testWithArray, [100, "test"]).then((value: string) => {})
129```
130
131
132## taskpool.execute
133
134execute(task: Task, priority?: Priority): Promise\<Object>
135
136Places a task in the internal queue of the task pool. The task is not executed immediately. It waits to be distributed to the worker thread for execution. In this mode, you can set the task priority and call **cancel()** to cancel the task. The task cannot be a task in a task group or serial queue. This API can be called only once for a continuous task, but multiple times for a non-continuous task.
137
138**System capability**: SystemCapability.Utils.Lang
139
140**Atomic service API**: This API can be used in atomic services since API version 11.
141
142**Parameters**
143
144| Name  | Type                 | Mandatory| Description                                      |
145| -------- | --------------------- | ---- | ---------------------------------------- |
146| task     | [Task](#task)         | Yes  | Task to be executed.                 |
147| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
148
149**Return value**
150
151| Type             | Description             |
152| ----------------  | ---------------- |
153| Promise\<Object> | Promise used to return an object that carries the function execution result.|
154
155**Error codes**
156
157For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
158
159| ID| Error Message                                    |
160| -------- | ------------------------------------------- |
161| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
162| 10200006 | An exception occurred during serialization. |
163| 10200014 | The function is not marked as concurrent.     |
164| 10200051 | The periodic task cannot be executed again. |
165
166**Example**
167
168```ts
169@Concurrent
170function printArgs(args: number): number {
171    console.info("printArgs: " + args);
172    return args;
173}
174
175let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
176let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
177let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
178taskpool.execute(task1, taskpool.Priority.LOW).then((value: Object) => {
179  console.info("taskpool result1: " + value);
180});
181taskpool.execute(task2, taskpool.Priority.MEDIUM).then((value: Object) => {
182  console.info("taskpool result2: " + value);
183});
184taskpool.execute(task3, taskpool.Priority.HIGH).then((value: Object) => {
185  console.info("taskpool result3: " + value);
186});
187```
188
189
190## taskpool.execute<sup>13+</sup>
191
192execute<A extends Array\<Object>, R>(task: GenericsTask<A, R>, priority?: Priority): Promise\<R>
193
194Verifies the passed-in parameter types and return value type of a concurrent function, and places the generic task in the internal queue of the task pool.
195
196**System capability**: SystemCapability.Utils.Lang
197
198**Atomic service API**: This API can be used in atomic services since API version 13.
199
200**Parameters**
201
202| Name  | Type                 | Mandatory| Description                                      |
203| -------- | --------------------- | ---- | ---------------------------------------- |
204| task     | [GenericsTask](#genericstask13)         | Yes  | Generic task to be executed.                 |
205| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
206
207**Return value**
208
209| Type             | Description             |
210| ----------------  | ---------------- |
211| Promise\<R> | Promise used to return an object that carries the function execution result.|
212
213**Error codes**
214
215For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
216
217| ID| Error Message                                    |
218| -------- | ------------------------------------------- |
219| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
220| 10200006 | An exception occurred during serialization. |
221| 10200014 | The function is not marked as concurrent.     |
222| 10200051 | The periodic task cannot be executed again. |
223
224**Example**
225
226```ts
227@Concurrent
228function printArgs(args: number): number {
229    console.info("printArgs: " + args);
230    return args;
231}
232
233let task1: taskpool.Task = new taskpool.GenericsTask<[number], number>(printArgs, 100); // 100: test number
234let task2: taskpool.Task = new taskpool.GenericsTask<[number], number>(printArgs, 200); // 200: test number
235let task3: taskpool.Task = new taskpool.GenericsTask<[number], number>(printArgs, 300); // 300: test number
236taskpool.execute<[number], number>(task1, taskpool.Priority.LOW).then((value: number) => {
237  console.info("taskpool result1: " + value);
238});
239taskpool.execute<[number], number>(task2, taskpool.Priority.MEDIUM).then((value: number) => {
240  console.info("taskpool result2: " + value);
241});
242taskpool.execute<[number], number>(task3, taskpool.Priority.HIGH).then((value: number) => {
243  console.info("taskpool result3: " + value);
244});
245```
246
247
248## taskpool.execute<sup>10+</sup>
249
250execute(group: TaskGroup, priority?: Priority): Promise<Object[]>
251
252Places a task group in the internal queue of the task pool. The tasks in the task group are not executed immediately. They wait to be distributed to the worker thread for execution. After all tasks in the task group are executed, a result array is returned. This API applies when you want to execute a group of associated tasks.
253
254**System capability**: SystemCapability.Utils.Lang
255
256**Atomic service API**: This API can be used in atomic services since API version 11.
257
258**Parameters**
259
260| Name    | Type                       | Mandatory| Description                                                          |
261| --------- | --------------------------- | ---- | -------------------------------------------------------------- |
262| group     | [TaskGroup](#taskgroup10)     | Yes  | Task group to be executed.                                     |
263| priority  | [Priority](#priority)       | No  | Priority of the task group. The default value is **taskpool.Priority.MEDIUM**.|
264
265**Return value**
266
267| Type                | Description                              |
268| ----------------    | ---------------------------------- |
269| Promise\<Object[]>  | Promise used to return an object array that carries the function execution result.|
270
271**Error codes**
272
273For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
274
275| ID| Error Message                                    |
276| -------- | ------------------------------------------- |
277| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
278| 10200006 | An exception occurred during serialization. |
279
280**Example**
281
282```ts
283@Concurrent
284function printArgs(args: number): number {
285    console.info("printArgs: " + args);
286    return args;
287}
288
289let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
290taskGroup1.addTask(printArgs, 10); // 10: test number
291taskGroup1.addTask(printArgs, 20); // 20: test number
292taskGroup1.addTask(printArgs, 30); // 30: test number
293
294let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
295let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
296let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
297let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
298taskGroup2.addTask(task1);
299taskGroup2.addTask(task2);
300taskGroup2.addTask(task3);
301taskpool.execute(taskGroup1).then((res: Array<Object>) => {
302  console.info("taskpool execute res is:" + res);
303});
304taskpool.execute(taskGroup2).then((res: Array<Object>) => {
305  console.info("taskpool execute res is:" + res);
306});
307```
308
309## taskpool.executeDelayed<sup>11+</sup>
310
311executeDelayed(delayTime: number, task: Task, priority?: Priority): Promise\<Object>
312
313Executes a task after a given delay. In this mode, you can set the task priority and call **cancel()** to cancel the task. The task cannot be a task in a task group or serial queue, or a periodic task. This API can be called only once for a continuous task, but multiple times for a non-continuous task.
314
315**System capability**: SystemCapability.Utils.Lang
316
317**Atomic service API**: This API can be used in atomic services since API version 11.
318
319**Parameters**
320
321| Name      | Type         | Mandatory| Description                |
322| ----------- | ------------- | ---- | -------------------- |
323| delayTime   | number        | Yes  | Delay, in ms. |
324| task        | [Task](#task) | Yes  | Task to be executed with a delay.|
325| priority    | [Priority](#priority)       | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
326
327**Return value**
328
329| Type                | Description                              |
330| ----------------    | ---------------------------------- |
331| Promise\<Object>  | Promise used to return an object that carries the function execution result.|
332
333**Error codes**
334
335For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
336
337| ID  | Error Message                        |
338| --------- | -------------------------------- |
339| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
340| 10200006 | An exception occurred during serialization. |
341| 10200014 | The function is not marked as concurrent. |
342| 10200028 | The delayTime is less than zero. |
343| 10200051 | The periodic task cannot be executed again. |
344
345**Example**
346
347```ts
348// import BusinessError
349import { BusinessError } from '@kit.BasicServicesKit'
350
351@Concurrent
352function printArgs(args: number): void {
353    console.info("printArgs: " + args);
354}
355
356let t: number = Date.now();
357console.info("taskpool start time is: " + t);
358let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
359taskpool.executeDelayed(1000, task).then(() => { // 1000:delayTime is 1000ms
360  console.info("taskpool execute success");
361}).catch((e: BusinessError) => {
362  console.error(`taskpool execute: Code: ${e.code}, message: ${e.message}`);
363})
364```
365
366
367## taskpool.executeDelayed<sup>13+</sup>
368
369executeDelayed<A extends Array\<Object>, R>(delayTime: number, task: GenericsTask\<A, R>, priority?: Priority): Promise\<R>
370
371Verifies the passed-in parameter types and return value type of a concurrent function, and executes the generic task with a delay.
372
373**System capability**: SystemCapability.Utils.Lang
374
375**Atomic service API**: This API can be used in atomic services since API version 13.
376
377**Parameters**
378
379| Name      | Type         | Mandatory| Description                |
380| ----------- | ------------- | ---- | -------------------- |
381| delayTime   | number        | Yes  | Delay, in ms. |
382| task        | [GenericsTask](#genericstask13) | Yes  | Generic task to be executed with a delay.|
383| priority    | [Priority](#priority)       | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
384
385**Return value**
386
387| Type                | Description                              |
388| ----------------    | ---------------------------------- |
389| Promise\<R>  | Promise used to return an object that carries the function execution result.|
390
391**Error codes**
392
393For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
394
395| ID  | Error Message                        |
396| --------- | -------------------------------- |
397| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
398| 10200028 | The delayTime is less than zero. |
399| 10200051 | The periodic task cannot be executed again. |
400
401**Example**
402
403```ts
404// import BusinessError
405import { BusinessError } from '@kit.BasicServicesKit'
406
407@Concurrent
408function printArgs(args: number): string {
409    console.info("printArgs: " + args);
410    return "success";
411}
412
413let task: taskpool.Task = new taskpool.GenericsTask<[number], string>(printArgs, 100); // 100: test number
414taskpool.executeDelayed<[number], string>(1000, task).then((res: string) => { // 1000:delayTime is 1000ms
415  console.info("taskpool execute success");
416}).catch((e: BusinessError) => {
417  console.error(`taskpool execute: Code: ${e.code}, message: ${e.message}`);
418})
419```
420
421
422## taskpool.executePeriodically<sup>12+</sup>
423
424executePeriodically(period: number, task: Task, priority?: Priority): void
425
426Executes a task periodically.
427
428In this execution mode, you can set the task priority and call **cancel()** to cancel the execution.
429
430A periodic task cannot be a task in a task group or serial queue. It cannot call **execute()** again or have a dependency relationship.
431
432**System capability**: SystemCapability.Utils.Lang
433
434**Atomic service API**: This API can be used in atomic services since API version 12.
435
436**Parameters**
437
438| Name      | Type         | Mandatory | Description                |
439| -----------  | ------------- | ----- | -------------------- |
440| period       | number        | Yes   | Execution period, in ms. |
441| task         | [Task](#task) | Yes   | Task to be executed.|
442| priority     | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
443
444
445**Error codes**
446
447For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
448
449| ID  | Error Message                        |
450| ---------- | -------------------------------- |
451| 401        | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
452| 10200006   | An exception occurred during serialization. |
453| 10200014   | The function is not marked as concurrent. |
454| 10200028   | The period is less than zero. |
455| 10200050   | The concurrent task has been executed and cannot be executed periodically. |
456
457
458**Example**
459
460```ts
461@Concurrent
462function printArgs(args: number): void {
463  console.info("printArgs: " + args);
464}
465
466@Concurrent
467function testExecutePeriodically(args: number): void {
468  let t = Date.now();
469  while ((Date.now() - t) < args) {
470    continue;
471  }
472  taskpool.Task.sendData(args); // Send a message to the host thread.
473}
474
475function printResult(data: number): void {
476  console.info("taskpool: data is: " + data);
477}
478
479function taskpoolTest() {
480  try {
481    let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
482    taskpool.executePeriodically(1000, task); // 1000: period is 1000ms
483  } catch (e) {
484    console.error(`taskpool execute-1: Code: ${e.code}, message: ${e.message}`);
485  }
486
487  try {
488    let periodicTask: taskpool.Task = new taskpool.Task(testExecutePeriodically, 200); // 200: test number
489    periodicTask.onReceiveData(printResult);
490    taskpool.executePeriodically(1000, periodicTask); // 1000: period is 1000ms
491  } catch (e) {
492    console.error(`taskpool execute-2: Code: ${e.code}, message: ${e.message}`);
493  }
494}
495
496taskpoolTest();
497```
498
499
500## taskpool.executePeriodically<sup>13+</sup>
501
502executePeriodically<A extends Array\<Object>, R>(period: number, task: GenericsTask\<A, R>, priority?: Priority): void
503
504Verifies the passed-in parameter types and return value type of a concurrent function, and executes the generic task periodically at an interval specified by **period**.
505
506
507**System capability**: SystemCapability.Utils.Lang
508
509**Atomic service API**: This API can be used in atomic services since API version 13.
510
511**Parameters**
512
513| Name      | Type         | Mandatory | Description                |
514| -----------  | ------------- | ----- | -------------------- |
515| period       | number        | Yes   | Execution period, in ms. |
516| task         | [GenericsTask](#genericstask13) | Yes   | Generic task to be executed periodically.|
517| priority     | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
518
519
520**Error codes**
521
522For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
523
524| ID  | Error Message                        |
525| ---------- | -------------------------------- |
526| 401        | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
527| 10200006   | An exception occurred during serialization. |
528| 10200014   | The function is not marked as concurrent. |
529| 10200028   | The period is less than zero. |
530| 10200050   | The concurrent task has been executed and cannot be executed periodically. |
531
532
533**Example**
534
535```ts
536@Concurrent
537function printArgs(args: number): void {
538  console.info("printArgs: " + args);
539}
540
541@Concurrent
542function testExecutePeriodically(args: number): void {
543  let t = Date.now();
544  while ((Date.now() - t) < args) {
545    continue;
546  }
547  taskpool.Task.sendData(args); // Send a message to the host thread.
548}
549
550function printResult(data: number): void {
551  console.info("taskpool: data is: " + data);
552}
553
554function taskpoolTest() {
555  try {
556    let task: taskpool.Task = new taskpool.GenericsTask<[number], void>(printArgs, 100); // 100: test number
557    taskpool.executePeriodically<[number], void>(1000, task); // 1000: period is 1000ms
558  } catch (e) {
559    console.error(`taskpool execute-1: Code: ${e.code}, message: ${e.message}`);
560  }
561
562  try {
563    let periodicTask: taskpool.Task = new taskpool.GenericsTask<[number], void>(testExecutePeriodically, 200); // 200: test number
564    periodicTask.onReceiveData(printResult);
565    taskpool.executePeriodically<[number], void>(1000, periodicTask); // 1000: period is 1000ms
566  } catch (e) {
567    console.error(`taskpool execute-2: Code: ${e.code}, message: ${e.message}`);
568  }
569}
570
571taskpoolTest();
572```
573
574
575## taskpool.cancel
576
577cancel(task: Task): void
578
579Cancels a task in the task pool. If the task is in the internal queue of the task pool, the task will not be executed after being canceled, and **undefined** is returned. If the task has been distributed to the worker thread of the task pool, canceling the task does not affect the task execution, and the execution result is returned in the catch branch. You can use **isCanceled()** to check the task cancellation status. In other words, **taskpool.cancel** takes effect before **taskpool.execute** or **taskpool.executeDelayed** is called.
580
581**System capability**: SystemCapability.Utils.Lang
582
583**Atomic service API**: This API can be used in atomic services since API version 11.
584
585**Parameters**
586
587| Name| Type         | Mandatory| Description                |
588| ------ | ------------- | ---- | -------------------- |
589| task   | [Task](#task) | Yes  | Task to cancel.|
590
591**Error codes**
592
593For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
594
595| ID| Error Message                                     |
596| -------- | -------------------------------------------- |
597| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
598| 10200015 | The task to cancel does not exist. |
599
600Since API version 10, error code 10200016 is not reported when this API is called.
601
602**Example of canceling an ongoing task**
603
604```ts
605@Concurrent
606function inspectStatus(arg: number): number {
607  // Check whether the task has been canceled and respond accordingly.
608  if (taskpool.Task.isCanceled()) {
609    console.info("task has been canceled before 2s sleep.");
610    return arg + 2;
611  }
612  // 2s sleep
613  let t: number = Date.now();
614  while (Date.now() - t < 2000) {
615    continue;
616  }
617  // Check again whether the task has been canceled and respond accordingly.
618  if (taskpool.Task.isCanceled()) {
619    console.info("task has been canceled after 2s sleep.");
620    return arg + 3;
621  }
622  return arg + 1;
623}
624
625function concurrentFunc() {
626  let task1: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
627  let task2: taskpool.Task = new taskpool.Task(inspectStatus, 200); // 200: test number
628  let task3: taskpool.Task = new taskpool.Task(inspectStatus, 300); // 300: test number
629  let task4: taskpool.Task = new taskpool.Task(inspectStatus, 400); // 400: test number
630  let task5: taskpool.Task = new taskpool.Task(inspectStatus, 500); // 500: test number
631  let task6: taskpool.Task = new taskpool.Task(inspectStatus, 600); // 600: test number
632  taskpool.execute(task1).then((res: Object)=>{
633    console.info("taskpool test result: " + res);
634  });
635  taskpool.execute(task2);
636  taskpool.execute(task3);
637  taskpool.execute(task4);
638  taskpool.execute(task5);
639  taskpool.execute(task6);
640  // Cancel the task 1s later.
641  setTimeout(()=>{
642    try {
643      taskpool.cancel(task1);
644    } catch (e) {
645      console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
646    }
647  }, 1000);
648}
649
650concurrentFunc();
651```
652
653## taskpool.cancel<sup>10+</sup>
654
655cancel(group: TaskGroup): void
656
657Cancels a task group in the task pool. If a task group is canceled before all the tasks in it are finished, **undefined** is returned.
658
659**System capability**: SystemCapability.Utils.Lang
660
661**Atomic service API**: This API can be used in atomic services since API version 11.
662
663**Parameters**
664
665| Name  | Type                   | Mandatory| Description                |
666| ------- | ----------------------- | ---- | -------------------- |
667| group   | [TaskGroup](#taskgroup10) | Yes  | Task group to cancel.|
668
669**Error codes**
670
671For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
672
673| ID| Error Message                                                |
674| -------- | ------------------------------------------------------- |
675| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
676| 10200018 | The task group to cancel does not exist.      |
677
678**Example**
679
680```ts
681@Concurrent
682function printArgs(args: number): number {
683  let t: number = Date.now();
684  while (Date.now() - t < 2000) {
685    continue;
686  }
687  console.info("printArgs: " + args);
688  return args;
689}
690
691function concurrentFunc() {
692  let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
693  taskGroup1.addTask(printArgs, 10); // 10: test number
694  let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
695  taskGroup2.addTask(printArgs, 100); // 100: test number
696  taskpool.execute(taskGroup1).then((res: Array<Object>)=>{
697    console.info("taskGroup1 res is:" + res);
698  });
699  taskpool.execute(taskGroup2).then((res: Array<Object>)=>{
700    console.info("taskGroup2 res is:" + res);
701  });
702  setTimeout(()=>{
703    try {
704      taskpool.cancel(taskGroup2);
705    } catch (e) {
706      console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
707    }
708  }, 1000);
709}
710
711concurrentFunc();
712```
713
714## taskpool.terminateTask<sup>12+</sup>
715
716terminateTask(longTask: LongTask): void
717
718Terminates a continuous task in the task pool. It is called after the continuous task is complete. After the task is terminated, the thread that executes the task may be reclaimed.
719
720**System capability**: SystemCapability.Utils.Lang
721
722**Atomic service API**: This API can be used in atomic services since API version 12.
723
724**Parameters**
725
726| Name| Type         | Mandatory| Description                |
727| ------ | ------------- | ---- | -------------------- |
728| longTask   | [LongTask](#longtask12) | Yes  | Continuous task to terminate.|
729
730**Error codes**
731
732For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
733
734| ID| Error Message|
735| -------- | -------- |
736| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
737
738**Example**
739
740```ts
741@Concurrent
742function longTask(arg: number): number {
743  let t: number = Date.now();
744  while (Date.now() - t < arg) {
745    continue;
746  }
747  console.info("longTask has been executed.");
748  return arg;
749}
750
751function concurrentFunc() {
752  let task1: taskpool.LongTask = new taskpool.LongTask(longTask, 1000); // 1000: sleep time
753  taskpool.execute(task1).then((res: Object)=>{
754    taskpool.terminateTask(task1);
755    console.info("taskpool longTask result: " + res);
756  });
757}
758
759concurrentFunc();
760```
761
762## taskpool.isConcurrent<sup>12+</sup>
763
764isConcurrent(func: Function): boolean
765
766Checks whether a function is a concurrent function.
767
768**System capability**: SystemCapability.Utils.Lang
769
770**Atomic service API**: This API can be used in atomic services since API version 12.
771
772**Parameters**
773
774| Name| Type         | Mandatory| Description                |
775| ------ | ------------- | ---- | -------------------- |
776| func   | Function | Yes  | Function to check.|
777
778**Return value**
779
780| Type   | Description                                |
781| ------- | ------------------------------------ |
782| boolean | **true**: The function is a concurrent function, that is, a function decorated with [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator).<br>**false**: The function is not a concurrent function.|
783
784**Error codes**
785
786For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
787
788| ID| Error Message|
789| -------- | -------- |
790| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
791
792**Example**
793
794```ts
795@Concurrent
796function test() {}
797
798let result: Boolean = taskpool.isConcurrent(test)
799console.info("result is: " + result)
800```
801
802## taskpool.getTaskPoolInfo<sup>10+</sup>
803
804getTaskPoolInfo(): TaskPoolInfo
805
806Obtains internal information about this task pool, including thread information and task information.
807
808**System capability**: SystemCapability.Utils.Lang
809
810**Atomic service API**: This API can be used in atomic services since API version 11.
811
812**Return value**
813
814| Type                               | Description               |
815| ----------------------------------- | ------------------ |
816| [TaskPoolInfo](#taskpoolinfo10)   | Internal information about the task pool.  |
817
818**Example**
819
820```ts
821let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
822```
823
824## Priority
825
826Enumerates the priorities available for created tasks. The task priority applies during task execution. The worker thread priority is updated with the task priority. For details about the mappings, see [QoS Level](../../napi/qos-guidelines.md#qos-level).
827
828**System capability**: SystemCapability.Utils.Lang
829
830| Name| Value| Description|
831| -------- | -------- | -------- |
832| HIGH   | 0    | The task has a high priority.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
833| MEDIUM | 1 | The task has a medium priority.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
834| LOW | 2 | The task has a low priority.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
835| IDLE<sup>12+</sup> | 3 | The task is a background task.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
836
837**Example**
838
839```ts
840@Concurrent
841function printArgs(args: number): number {
842  let t: number = Date.now();
843  while (Date.now() - t < 1000) { // 1000: delay 1s
844    continue;
845  }
846  console.info("printArgs: " + args);
847  return args;
848}
849
850let allCount = 100; // 100: test number
851let taskArray: Array<taskpool.Task> = [];
852// Create 400 tasks and add them to taskArray.
853for (let i: number = 0; i < allCount; i++) {
854  let task1: taskpool.Task = new taskpool.Task(printArgs, i);
855  taskArray.push(task1);
856  let task2: taskpool.Task = new taskpool.Task(printArgs, i * 10); // 10: test number
857  taskArray.push(task2);
858  let task3: taskpool.Task = new taskpool.Task(printArgs, i * 100); // 100: test number
859  taskArray.push(task3);
860  let task4: taskpool.Task = new taskpool.Task(printArgs, i * 1000); // 1000: test number
861  taskArray.push(task4);
862}
863
864// Obtain different tasks from taskArray and specify different priorities for execution.
865for (let i: number = 0; i < taskArray.length; i+=4) { // 4: Four tasks are executed each time. When obtaining tasks cyclically, obtain the four items following the last batch to ensure that different tasks are obtained each time.
866  taskpool.execute(taskArray[i], taskpool.Priority.HIGH);
867  taskpool.execute(taskArray[i + 1], taskpool.Priority.LOW);
868  taskpool.execute(taskArray[i + 2], taskpool.Priority.MEDIUM);
869  taskpool.execute(taskArray[i + 3], taskpool.Priority.IDLE);
870}
871```
872
873## Task
874
875Implements a task. Before calling any APIs in **Task**, you must use [constructor](#constructor) to create a **Task** instance. A task can be executed for multiple times, placed in a task group or serial queue for execution, or added with dependencies for execution.
876
877### Attributes
878
879**System capability**: SystemCapability.Utils.Lang
880
881**Atomic service API**: This API can be used in atomic services since API version 11.
882
883| Name                | Type      | Readable| Writable| Description                                                        |
884| -------------------- | --------- | ---- | ---- | ------------------------------------------------------------ |
885| function             | Function  | Yes  | Yes  | Function to be passed in during task creation. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).|
886| arguments            | Object[]  | Yes  | Yes  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). |
887| name<sup>11+</sup>   | string    | Yes  | No  | Name of the task specified when the task is created. |
888| totalDuration<sup>11+</sup>  | number    | Yes  | No  | Total execution time of the task. |
889| ioDuration<sup>11+</sup>     | number    | Yes  | No  | Asynchronous I/O time of the task. |
890| cpuDuration<sup>11+</sup>    | number    | Yes  | No  | CPU time of the task. |
891
892### constructor
893
894constructor(func: Function, ...args: Object[])
895
896A constructor used to create a **Task** instance.
897
898**System capability**: SystemCapability.Utils.Lang
899
900**Atomic service API**: This API can be used in atomic services since API version 11.
901
902**Parameters**
903
904| Name| Type     | Mandatory| Description                                                                 |
905| ------ | --------- | ---- | -------------------------------------------------------------------- |
906| func   | Function  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
907| args   | Object[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
908
909**Error codes**
910
911For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
912
913| ID| Error Message                                |
914| -------- | --------------------------------------- |
915| 401      | The input parameters are invalid. |
916| 10200014 | The function is not marked as concurrent. |
917
918**Example**
919
920```ts
921@Concurrent
922function printArgs(args: number): number {
923  console.info("printArgs: " + args);
924  return args;
925}
926
927let task: taskpool.Task = new taskpool.Task(printArgs, "this is my first Task");
928```
929
930### constructor<sup>11+</sup>
931
932constructor(name: string, func: Function, ...args: Object[])
933
934A constructor used to create a **Task** instance, with the task name specified.
935
936**System capability**: SystemCapability.Utils.Lang
937
938**Atomic service API**: This API can be used in atomic services since API version 11.
939
940**Parameters**
941
942| Name| Type    | Mandatory| Description                                                        |
943| ------ | -------- | ---- | ------------------------------------------------------------ |
944| name   | string   | Yes  | Task name.                                                  |
945| func   | Function  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
946| args   | Object[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
947
948**Error codes**
949
950For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
951
952| ID| Error Message                               |
953| -------- | --------------------------------------- |
954| 401      | The input parameters are invalid. |
955| 10200014 | The function is not marked as concurrent. |
956
957**Example**
958
959```ts
960@Concurrent
961function printArgs(args: string): string {
962  console.info("printArgs: " + args);
963  return args;
964}
965
966let taskName: string = "taskName";
967let task: taskpool.Task = new taskpool.Task(taskName, printArgs, "this is my first Task");
968let name: string = task.name;
969```
970
971### isCanceled<sup>10+</sup>
972
973static isCanceled(): boolean
974
975Checks whether the running task is canceled. Before using this API, you must create a **Task** instance.
976
977**System capability**: SystemCapability.Utils.Lang
978
979**Atomic service API**: This API can be used in atomic services since API version 11.
980
981**Return value**
982
983| Type   | Description                                |
984| ------- | ------------------------------------ |
985| boolean | Returns **true** if the running task is canceled; returns **false** otherwise.|
986
987**Example**
988
989```ts
990@Concurrent
991function inspectStatus(arg: number): number {
992    // do something
993    if (taskpool.Task.isCanceled()) {
994      console.info("task has been canceled.");
995      // do something
996      return arg + 1;
997    }
998    // do something
999    return arg;
1000}
1001```
1002
1003> **NOTE**
1004>
1005> **isCanceled** must be used together with **taskpool.cancel**. If **cancel** is not called, **isCanceled** returns **false** by default.
1006
1007**Example**
1008
1009```ts
1010@Concurrent
1011function inspectStatus(arg: number): number {
1012  // Check whether the task has been canceled and respond accordingly.
1013  if (taskpool.Task.isCanceled()) {
1014    console.info("task has been canceled before 2s sleep.");
1015    return arg + 2;
1016  }
1017  // Wait for 2s.
1018  let t: number = Date.now();
1019  while (Date.now() - t < 2000) {
1020    continue;
1021  }
1022  // Check again whether the task has been canceled and respond accordingly.
1023  if (taskpool.Task.isCanceled()) {
1024    console.info("task has been canceled after 2s sleep.");
1025    return arg + 3;
1026  }
1027  return arg + 1;
1028}
1029
1030let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
1031taskpool.execute(task).then((res: Object)=>{
1032  console.info("taskpool test result: " + res);
1033}).catch((err: string) => {
1034  console.error("taskpool test occur error: " + err);
1035});
1036// If cancel is not called, isCanceled() returns false by default, and the task execution result is 101.
1037```
1038
1039### setTransferList<sup>10+</sup>
1040
1041setTransferList(transfer?: ArrayBuffer[]): void
1042
1043Sets the task transfer list. Before using this API, you must create a **Task** instance. If this API is not called, the ArrayBuffer in the data is transferred by default.
1044
1045> **NOTE**
1046>
1047> This API is used to set the task transfer list in the form of **ArrayBuffer** in the task pool. The **ArrayBuffer** instance does not copy the content in the task to the worker thread during transfer. Instead, it transfers the buffer control right to the worker thread. After the transfer, the **ArrayBuffer** instance becomes invalid. An empty **ArrayBuffer** will not be transferred.
1048
1049**System capability**: SystemCapability.Utils.Lang
1050
1051**Atomic service API**: This API can be used in atomic services since API version 11.
1052
1053**Parameters**
1054
1055| Name  | Type          | Mandatory| Description                                         |
1056| -------- | ------------- | ---- | --------------------------------------------- |
1057| transfer | ArrayBuffer[] | No  | **ArrayBuffer** instance holding the objects to transfer. The default value is an empty array.|
1058
1059**Error codes**
1060
1061For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1062
1063| ID| Error Message                                                       |
1064| -------- | -------------------------------------------------------------- |
1065| 401      | Parameter error. Possible causes: 1. Incorrect parameter types; 2. Parameter verification failed. |
1066| 10200029 | An ArrayBuffer cannot be set as both a transfer list and a clone list. |
1067
1068**Example**
1069
1070```ts
1071@Concurrent
1072function testTransfer(arg1: ArrayBuffer, arg2: ArrayBuffer): number {
1073  console.info("testTransfer arg1 byteLength: " + arg1.byteLength);
1074  console.info("testTransfer arg2 byteLength: " + arg2.byteLength);
1075  return 100;
1076}
1077
1078let buffer: ArrayBuffer = new ArrayBuffer(8);
1079let view: Uint8Array = new Uint8Array(buffer);
1080let buffer1: ArrayBuffer = new ArrayBuffer(16);
1081let view1: Uint8Array = new Uint8Array(buffer1);
1082
1083console.info("testTransfer view byteLength: " + view.byteLength);
1084console.info("testTransfer view1 byteLength: " + view1.byteLength);
1085// The execution result is as follows:
1086// testTransfer view byteLength: 8
1087// testTransfer view1 byteLength: 16
1088
1089let task: taskpool.Task = new taskpool.Task(testTransfer, view, view1);
1090task.setTransferList([view.buffer, view1.buffer]);
1091taskpool.execute(task).then((res: Object)=>{
1092  console.info("test result: " + res);
1093}).catch((e: string)=>{
1094  console.error("test catch: " + e);
1095})
1096console.info("testTransfer view2 byteLength: " + view.byteLength);
1097console.info("testTransfer view3 byteLength: " + view1.byteLength);
1098// The value is 0 after transfer. The execution result is as follows:
1099// testTransfer view2 byteLength: 0
1100// testTransfer view3 byteLength: 0
1101```
1102
1103
1104### setCloneList<sup>11+</sup>
1105
1106setCloneList(cloneList: Object[] | ArrayBuffer[]): void
1107
1108Sets the task clone list. Before using this API, you must create a **Task** instance.
1109
1110> **NOTE**
1111>
1112> This API must be used together with the [@Sendable decorator](../../arkts-utils/arkts-sendable.md#sendable-decorator). Otherwise, an exception is thrown.
1113
1114**System capability**: SystemCapability.Utils.Lang
1115
1116**Atomic service API**: This API can be used in atomic services since API version 11.
1117
1118**Parameters**
1119
1120| Name   | Type                     | Mandatory| Description                                         |
1121| --------- | ------------------------ | ---- | --------------------------------------------- |
1122| cloneList | Object[] \| ArrayBuffer[]  | Yes| - The type of the passed-in array must be [sendable data types](../../arkts-utils/arkts-sendable.md#sendable-data-types) or ArrayBuffer.<br>- All [Sendable class](../../arkts-utils/arkts-sendable.md#sendable-class) instances or ArrayBuffer objects passed in to **cloneList** are transferred in copy mode between threads. This means that any modification to the destination objects does not affect the original objects.|
1123
1124**Error codes**
1125
1126For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1127
1128| ID| Error Message                                                       |
1129| -------- | -------------------------------------------------------------- |
1130| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1131| 10200029 | An ArrayBuffer cannot be set as both a transfer list and a clone list. |
1132
1133**Example**
1134
1135```ts
1136// sendable.ets
1137// Define two Sendable classes: BaseClass and its child class DeriveClass.
1138@Sendable
1139export class BaseClass {
1140  private str: string = "sendable: BaseClass";
1141  static num :number = 10;
1142  str1: string = "sendable: this is BaseClass's string";
1143  num1: number = 5;
1144  isDone1: boolean = false;
1145
1146  private fibonacciRecursive(n: number): number {
1147    if (n <= 1) {
1148      return n;
1149    } else {
1150      return this.fibonacciRecursive(n - 1) + this.fibonacciRecursive(n - 2);
1151    }
1152  }
1153
1154  private privateFunc(num: number): number{
1155    let res: number = this.fibonacciRecursive(num);
1156    console.info("sendable: BaseClass privateFunc res is: " + res);
1157    return res;
1158  }
1159
1160  publicFunc(num: number): number {
1161    return this.privateFunc(num);
1162  }
1163
1164  get GetNum(): number {
1165    return this.num1;
1166  }
1167  set SetNum(num: number) {
1168    this.num1 = num;
1169  }
1170
1171  constructor(){
1172    console.info(this.str);
1173    this.isDone1 = true;
1174  }
1175}
1176
1177@Sendable
1178export class DeriveClass extends BaseClass {
1179  name: string = "sendable: this is DeriveClass";
1180  printName() {
1181    console.info(this.name);
1182  }
1183  constructor() {
1184    super();
1185  }
1186}
1187```
1188
1189<!--code_no_check-->
1190```ts
1191// index.ets
1192// The host thread (UI main thread) calls the methods of BaseClass and DeriveClass in the task pool thread and accesses their attributes.
1193import { taskpool } from '@kit.ArkTS'
1194import { BusinessError } from '@kit.BasicServicesKit'
1195import { BaseClass, DeriveClass } from './sendable'
1196
1197@Concurrent
1198function testFunc(arr: Array<BaseClass>, num: number): number {
1199  let baseInstance1 = arr[0];
1200  console.info("sendable: str1 is: " + baseInstance1.str1);
1201  baseInstance1.SetNum = 100;
1202  console.info("sendable: num1 is: " + baseInstance1.GetNum);
1203  console.info("sendable: isDone1 is: " + baseInstance1.isDone1);
1204  // Obtain the result of the item specified by num from Fibonacci sequence.
1205  let res: number = baseInstance1.publicFunc(num);
1206  return res;
1207}
1208
1209@Concurrent
1210function printLog(arr: Array<DeriveClass>): void {
1211  let deriveInstance = arr[0];
1212  deriveInstance.printName();
1213}
1214
1215@Entry
1216@Component
1217struct Index {
1218  @State message: string = 'Hello World'
1219
1220  build() {
1221    Row() {
1222      Column() {
1223        Text(this.message)
1224          .fontSize(50)
1225          .fontWeight(FontWeight.Bold)
1226        Button() {
1227          Text("TaskPool Test")
1228        }.onClick(() => {
1229          // task1 calls BaseClass.str1/BaseClass.SetNum/BaseClass.GetNum/BaseClass.isDone1/BaseClass.publicFunc.
1230          let baseInstance1: BaseClass = new BaseClass();
1231          let array1 = new Array<BaseClass>();
1232          array1.push(baseInstance1);
1233          let task1 = new taskpool.Task(testFunc, array1, 10);
1234          task1.setCloneList(array1);
1235          taskpool.execute(task1).then((res: Object) => {
1236            console.info("sendable: task1 res is: " + res);
1237          }).catch((e:BusinessError) => {
1238            console.error(`sendable: task1 execute Code is ${e.code}, message is ${e.message}`);
1239          })
1240
1241          // task2 calls DeriveClass.printName.
1242          let deriveInstance: DeriveClass = new DeriveClass();
1243          let array2 = new Array<DeriveClass>();
1244          array2.push(deriveInstance);
1245          let task2 = new taskpool.Task(printLog, array2);
1246          task2.setCloneList(array2);
1247          taskpool.execute(task2).then(() => {
1248            console.info("sendable: task2 execute success");
1249          }).catch((e:BusinessError) => {
1250            console.error(`sendable: task2 execute Code is ${e.code}, message is ${e.message}`);
1251          })
1252        })
1253        .height('15%')
1254        .width('30%')
1255      }
1256      .width('100%')
1257    }
1258    .height('100%')
1259  }
1260}
1261```
1262
1263
1264### sendData<sup>11+</sup>
1265
1266static sendData(...args: Object[]): void
1267
1268Sends data to the host thread and triggers the registered callback. Before using this API, you must create a **Task** instance.
1269
1270> **NOTE**
1271>
1272> - The API is called in the TaskPool thread.
1273> - Do not use this API in a callback function.
1274> - Before calling this API, ensure that the callback function for processing data has been registered in the host thread.
1275
1276**System capability**: SystemCapability.Utils.Lang
1277
1278**Atomic service API**: This API can be used in atomic services since API version 11.
1279
1280**Parameters**
1281
1282| Name  | Type         | Mandatory| Description                                             |
1283| -------- | ------------- | ---- | ------------------------------------------------- |
1284| args     | Object[]      | No  | Data to be used as the input parameter of the registered callback. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
1285
1286**Error codes**
1287
1288For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1289
1290| ID| Error Message                                |
1291| -------- | --------------------------------------- |
1292| 401       | The input parameters are invalid. |
1293| 10200006  | An exception occurred during serialization. |
1294| 10200022  | The function is not called in the TaskPool thread. |
1295| 10200023  | The function is not called in the concurrent function. |
1296| 10200024  | The callback is not registered on the host side. |
1297
1298**Example**
1299
1300```ts
1301@Concurrent
1302function sendDataTest(num: number): number {
1303  let res: number = num * 10;
1304  taskpool.Task.sendData(res);
1305  return num;
1306}
1307
1308function printLog(data: number): void {
1309  console.info("taskpool: data is: " + data);
1310}
1311
1312async function taskpoolTest(): Promise<void> {
1313  try {
1314    let task: taskpool.Task = new taskpool.Task(sendDataTest, 1);
1315    task.onReceiveData(printLog);
1316    await taskpool.execute(task);
1317  } catch (e) {
1318    console.error(`taskpool: error code: ${e.code}, info: ${e.message}`);
1319  }
1320}
1321
1322taskpoolTest();
1323```
1324
1325
1326### onReceiveData<sup>11+</sup>
1327
1328onReceiveData(callback?: Function): void
1329
1330Registers a callback for a task to receive and process data from the worker thread. Before using this API, you must create a **Task** instance.
1331
1332> **NOTE**
1333>
1334> If multiple callbacks are registered for the same task, only the last registration takes effect.
1335
1336**System capability**: SystemCapability.Utils.Lang
1337
1338**Atomic service API**: This API can be used in atomic services since API version 11.
1339
1340**Parameters**
1341
1342| Name  | Type    | Mandatory| Description                                                        |
1343| -------- | -------- | ---- | ------------------------------------------------------------ |
1344| callback | Function | No  | Callback function for processing the data received. The data sent to the host thread is transferred to the callback as an input parameter. If no value is passed in, all the registered callbacks are canceled.|
1345
1346**Error codes**
1347
1348For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1349
1350| ID| Error Message|
1351| -------- | -------- |
1352| 401 | Parameter error. Possible causes: 1. Incorrect parameter types; 2. Parameter verification failed. |
1353
1354**Example**
1355
1356```ts
1357@Concurrent
1358function ConcurrentFunc(num: number): number {
1359  let res: number = num * 10;
1360  taskpool.Task.sendData(res);
1361  return num;
1362}
1363
1364function printLog(data: number): void {
1365  console.info("taskpool: data is: " + data);
1366}
1367
1368async function testFunc(): Promise<void> {
1369  try {
1370    let task: taskpool.Task = new taskpool.Task(ConcurrentFunc, 1);
1371    task.onReceiveData(printLog);
1372    await taskpool.execute(task);
1373  } catch (e) {
1374    console.error(`taskpool: error code: ${e.code}, info: ${e.message}`);
1375  }
1376}
1377
1378testFunc();
1379```
1380
1381### addDependency<sup>11+</sup>
1382
1383addDependency(...tasks: Task[]): void
1384
1385Adds dependent tasks for this task. Before using this API, you must create a **Task** instance. The task and its dependent tasks cannot be a task in a task group or serial queue, a task that has been executed, or a periodic task. A task with a dependency relationship (a task that depends on another task or a task that is depended on) cannot be executed multiple times.
1386
1387**System capability**: SystemCapability.Utils.Lang
1388
1389**Atomic service API**: This API can be used in atomic services since API version 11.
1390
1391**Parameters**
1392
1393| Name| Type            | Mandatory| Description              |
1394| ------ | --------------- | ---- | ------------------ |
1395| tasks  | [Task](#task)[] | No  | Array of tasks on which the current task depends. The default value is **undefined**.|
1396
1397**Error codes**
1398
1399For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1400
1401| ID| Error Message                       |
1402| -------- | ------------------------------- |
1403| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1404| 10200026 | There is a circular dependency. |
1405| 10200052 | The periodic task cannot have a dependency. |
1406
1407**Example**
1408
1409```ts
1410@Concurrent
1411function delay(args: number): number {
1412  let t: number = Date.now();
1413  while ((Date.now() - t) < 1000) {
1414	continue;
1415  }
1416  return args;
1417}
1418
1419let task1:taskpool.Task = new taskpool.Task(delay, 100);
1420let task2:taskpool.Task = new taskpool.Task(delay, 200);
1421let task3:taskpool.Task = new taskpool.Task(delay, 200);
1422
1423console.info("dependency: add dependency start");
1424task1.addDependency(task2);
1425task2.addDependency(task3);
1426console.info("dependency: add dependency end");
1427
1428console.info("dependency: start execute second")
1429taskpool.execute(task1).then(() => {
1430  console.info("dependency: second task1 success");
1431})
1432taskpool.execute(task2).then(() => {
1433  console.info("dependency: second task2 success");
1434})
1435taskpool.execute(task3).then(() => {
1436  console.info("dependency: second task3 success");
1437})
1438```
1439
1440### removeDependency<sup>11+</sup>
1441
1442removeDependency(...tasks: Task[]): void
1443
1444Removes dependent tasks for this task. Before using this API, you must create a **Task** instance.
1445
1446**System capability**: SystemCapability.Utils.Lang
1447
1448**Atomic service API**: This API can be used in atomic services since API version 11.
1449
1450**Parameters**
1451
1452| Name| Type  | Mandatory| Description              |
1453| ------ | ------ | ---- | ------------------ |
1454| tasks  | [Task](#task)[] | No  | Array of tasks on which the current task depends. The default value is **undefined**.|
1455
1456**Error codes**
1457
1458For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1459
1460| ID| Error Message                      |
1461| -------- | ------------------------------ |
1462| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1463| 10200027 | The dependency does not exist. |
1464| 10200052 | The periodic task cannot have a dependency. |
1465
1466**Example**
1467
1468```ts
1469@Concurrent
1470function delay(args: number): number {
1471  let t: number = Date.now();
1472  while ((Date.now() - t) < 1000) {
1473	continue;
1474  }
1475  return args;
1476}
1477
1478let task1:taskpool.Task = new taskpool.Task(delay, 100);
1479let task2:taskpool.Task = new taskpool.Task(delay, 200);
1480let task3:taskpool.Task = new taskpool.Task(delay, 200);
1481
1482console.info("dependency: add dependency start");
1483task1.addDependency(task2);
1484task2.addDependency(task3);
1485console.info("dependency: add dependency end");
1486console.info("dependency: remove dependency start");
1487task1.removeDependency(task2);
1488task2.removeDependency(task3);
1489console.info("dependency: remove dependency end");
1490
1491console.info("dependency: start execute")
1492taskpool.execute(task1).then(() => {
1493  console.info("dependency: task1 success");
1494})
1495taskpool.execute(task2).then(() => {
1496  console.info("dependency: task2 success");
1497})
1498taskpool.execute(task3).then(() => {
1499  console.info("dependency: task3 success");
1500})
1501```
1502
1503
1504### onEnqueued<sup>12+</sup>
1505
1506onEnqueued(callback: CallbackFunction): void
1507
1508Registers a callback function and calls it when a task is enqueued. The registration must be carried out before the task is executed. Otherwise, an exception is thrown.
1509
1510**System capability**: SystemCapability.Utils.Lang
1511
1512**Atomic service API**: This API can be used in atomic services since API version 12.
1513
1514**Parameters**
1515
1516| Name| Type  | Mandatory| Description              |
1517| ------ | ------ | ---- | ------------------ |
1518| callback  | [CallbackFunction](#callbackfunction12) | Yes  | Callback function to register.|
1519
1520**Error codes**
1521
1522For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1523
1524| ID| Error Message                      |
1525| -------- | ------------------------------ |
1526| 401       | The input parameters are invalid. |
1527| 10200034  | The executed task does not support the registration of listeners. |
1528
1529**Example**
1530
1531```ts
1532import { taskpool } from '@kit.ArkTS'
1533
1534@Concurrent
1535function delay(args: number): number {
1536  let t: number = Date.now();
1537  while ((Date.now() - t) < 1000) {
1538	continue;
1539  }
1540  return args;
1541}
1542
1543let task: taskpool.Task = new taskpool.Task(delay, 1);
1544task.onEnqueued(()=>{
1545  console.info("taskpool: onEnqueued")
1546});
1547taskpool.execute(task).then(()=> {
1548  console.info("taskpool: execute task success")
1549});
1550```
1551
1552
1553### onStartExecution<sup>12+</sup>
1554
1555onStartExecution(callback: CallbackFunction): void
1556
1557Registers a callback function and calls it when the execution of a task starts. The registration must be carried out before the task is executed. Otherwise, an exception is thrown.
1558
1559**System capability**: SystemCapability.Utils.Lang
1560
1561**Atomic service API**: This API can be used in atomic services since API version 12.
1562
1563**Parameters**
1564
1565| Name| Type  | Mandatory| Description              |
1566| ------ | ------ | ---- | ------------------ |
1567| callback  | [CallbackFunction](#callbackfunction12)  | Yes  | Callback function to register.|
1568
1569**Error codes**
1570
1571For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1572
1573| ID| Error Message                      |
1574| -------- | ------------------------------ |
1575| 401       | The input parameters are invalid. |
1576| 10200034  | The executed task does not support the registration of listeners. |
1577
1578**Example**
1579
1580```ts
1581import { taskpool } from '@kit.ArkTS'
1582
1583@Concurrent
1584function delay(args: number): number {
1585  let t: number = Date.now();
1586  while ((Date.now() - t) < 1000) {
1587	continue;
1588  }
1589  return args;
1590}
1591
1592let task: taskpool.Task = new taskpool.Task(delay, 1);
1593task.onStartExecution(()=>{
1594  console.info("taskpool: onStartExecution")
1595});
1596taskpool.execute(task).then(()=> {
1597  console.info("taskpool: execute task success")
1598});
1599```
1600
1601### onExecutionFailed<sup>12+</sup>
1602
1603onExecutionFailed(callback: CallbackFunctionWithError): void
1604
1605Registers a callback function and calls it when a task fails to be enqueued. The registration must be carried out before the task is executed. Otherwise, an exception is thrown.
1606
1607**System capability**: SystemCapability.Utils.Lang
1608
1609**Atomic service API**: This API can be used in atomic services since API version 12.
1610
1611**Parameters**
1612
1613| Name| Type  | Mandatory| Description              |
1614| ------ | ------ | ---- | ------------------ |
1615| callback  | [CallbackFunctionWithError](#callbackfunctionwitherror12)  | Yes  | Callback function to register.|
1616
1617**Error codes**
1618
1619For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1620
1621| ID| Error Message                      |
1622| -------- | ------------------------------ |
1623| 401       | The input parameters are invalid. |
1624| 10200034  | The executed task does not support the registration of listeners. |
1625
1626**Example**
1627
1628```ts
1629import { taskpool } from '@kit.ArkTS'
1630import { BusinessError } from '@kit.BasicServicesKit'
1631import { HashMap } from '@kit.ArkTS'
1632
1633@Concurrent
1634function test(args:number) {
1635  let t = Date.now()
1636  while ((Date.now() - t) < 100) {
1637    continue;
1638  }
1639  let hashMap1: HashMap<string, number> = new HashMap();
1640  hashMap1.set('a', args);
1641  return hashMap1;
1642}
1643
1644let task2 = new taskpool.Task(test, 1);
1645task2.onExecutionFailed((e:Error)=>{
1646  console.info("taskpool: onExecutionFailed error is " + e);
1647})
1648taskpool.execute(task2).then(()=>{
1649  console.info("taskpool: execute task success")
1650}).catch((e:BusinessError)=>{
1651  console.error(`taskpool: error code: ${e.code}, error info: ${e.message}`);
1652})
1653```
1654
1655### onExecutionSucceeded<sup>12+</sup>
1656
1657onExecutionSucceeded(callback: CallbackFunction): void
1658
1659Registers a callback function and calls it when a task is executed successfully. The registration must be carried out before the task is executed. Otherwise, an exception is thrown.
1660
1661**System capability**: SystemCapability.Utils.Lang
1662
1663**Atomic service API**: This API can be used in atomic services since API version 12.
1664
1665**Parameters**
1666
1667| Name| Type  | Mandatory| Description              |
1668| ------ | ------ | ---- | ------------------ |
1669| callback  | [CallbackFunction](#callbackfunction12)  | Yes  | Callback function to register.|
1670
1671**Error codes**
1672
1673For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1674
1675| ID| Error Message                      |
1676| -------- | ------------------------------ |
1677| 401       | The input parameters are invalid. |
1678| 10200034  | The executed task does not support the registration of listeners. |
1679
1680**Example**
1681
1682```ts
1683import { taskpool } from '@kit.ArkTS'
1684
1685@Concurrent
1686function delay(args: number): number {
1687  let t: number = Date.now();
1688  while ((Date.now() - t) < 1000) {
1689	  continue;
1690  }
1691  return args;
1692}
1693
1694let task: taskpool.Task = new taskpool.Task(delay, 1);
1695task.onExecutionSucceeded(()=>{
1696  console.info("taskpool: onExecutionSucceeded")
1697});
1698taskpool.execute(task).then(()=> {
1699  console.info("taskpool: execute task success")
1700});
1701```
1702
1703### isDone<sup>12+</sup>
1704
1705isDone(): boolean
1706
1707Checks whether the task is complete.
1708
1709**System capability**: SystemCapability.Utils.Lang
1710
1711**Atomic service API**: This API can be used in atomic services since API version 12.
1712
1713**Return value**
1714
1715| Type   | Description                                |
1716| ------- | ------------------------------------ |
1717| boolean | **true**: The task is complete.<br>**false**: The task is not complete.|
1718
1719**Example**
1720
1721```ts
1722@Concurrent
1723function inspectStatus(arg: number): number {
1724  // 2s sleep
1725  let t: number = Date.now();
1726  while (Date.now() - t < 1000) {
1727    continue;
1728  }
1729  return arg + 1;
1730}
1731
1732async function taskpoolCancel(): Promise<void> {
1733  let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
1734  taskpool.execute(task).then((res: Object)=>{
1735    console.info("taskpool test result: " + res);
1736  }).catch((err: string) => {
1737    console.error("taskpool test occur error: " + err);
1738  });
1739
1740  setTimeout(()=>{
1741    if (!task.isDone()) {
1742      taskpool.cancel(task);
1743    }
1744  }, 3000); // Wait for 3s to ensure that the task has been executed.
1745}
1746
1747taskpoolCancel();
1748```
1749
1750## CallbackFunction<sup>12+</sup>
1751
1752type CallbackFunction = () => void
1753
1754Describes a callback function.
1755
1756**System capability**: SystemCapability.Utils.Lang
1757
1758**Atomic service API**: This API can be used in atomic services since API version 12.
1759
1760
1761## CallbackFunctionWithError<sup>12+</sup>
1762
1763type CallbackFunctionWithError = (e: Error) => void
1764
1765Describes a callback function with an error message.
1766
1767**System capability**: SystemCapability.Utils.Lang
1768
1769**Atomic service API**: This API can be used in atomic services since API version 12.
1770**Parameters**
1771
1772| Name| Type  | Mandatory| Description              |
1773| ------ | ------ | ---- | ------------------ |
1774| e  | Error | Yes  | Error message.|
1775
1776
1777## LongTask<sup>12+</sup>
1778
1779**System capability**: SystemCapability.Utils.Lang
1780
1781Describes a continuous task. **LongTask** inherits from [Task](#task).
1782No upper limit is set for the execution time of a continuous task, and no timeout exception is thrown if a continuous task runs for a long period of time. However, a continuous task cannot be executed in a task group or executed for multiple times.
1783The thread for executing a continuous task exists until [terminateTask](#taskpoolterminatetask12) is called after the execution is complete. The thread is reclaimed when it is idle.
1784
1785**Example**
1786
1787```ts
1788@Concurrent
1789function printArgs(args: string): string {
1790  console.info("printArgs: " + args);
1791  return args;
1792}
1793
1794let task: taskpool.LongTask = new taskpool.LongTask(printArgs, "this is my first LongTask");
1795```
1796
1797
1798## GenericsTask<sup>13+</sup>
1799
1800**System capability**: SystemCapability.Utils.Lang
1801
1802Implements a generic task. **GenericsTask** inherits from [Task](#task).
1803
1804During the creation of a generic task, the passed-in parameter types and return value types of concurrent functions are verified in the compilation phase. Other behaviors are the same as those during the creation of a task.
1805
1806### constructor<sup>13+</sup>
1807
1808constructor(func: (...args: A) => R | Promise\<R>, ...args: A)
1809
1810A constructor used to create a **GenericsTask** object.
1811
1812**System capability**: SystemCapability.Utils.Lang
1813
1814**Atomic service API**: This API can be used in atomic services since API version 13.
1815
1816**Parameters**
1817
1818| Name| Type     | Mandatory| Description                                                                 |
1819| ------ | --------- | ---- | -------------------------------------------------------------------- |
1820| func   | (...args: A) => R \| Promise\<R>  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
1821| args   | A | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
1822
1823**Error codes**
1824
1825For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1826
1827| ID| Error Message                                |
1828| -------- | --------------------------------------- |
1829| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
1830| 10200014 | The function is not marked as concurrent. |
1831
1832**Example**
1833
1834```ts
1835@Concurrent
1836function printArgs(args: string): string {
1837  console.info("printArgs: " + args);
1838  return args;
1839}
1840
1841@Concurrent
1842function testWithThreeParams(a: number, b: string, c: number): string {
1843  return b;
1844}
1845
1846@Concurrent
1847function testWithArray(args: [number, string]): string {
1848  return "success";
1849}
1850
1851let task1: taskpool.Task = new taskpool.GenericsTask<[string], string>(printArgs, "this is my first LongTask");
1852
1853let task2: taskpool.Task = new taskpool.GenericsTask<[number, string, number], string>(testWithThreeParams, 100, "test", 100);
1854
1855let task3: taskpool.Task = new taskpool.GenericsTask<[[number, string]], string>(testWithArray, [100, "test"]);
1856```
1857
1858### constructor<sup>13+</sup>
1859
1860constructor(name: string, func: (...args: A) => R | Promise\<R>, ...args: A)
1861
1862A constructor used to create a **GenericsTask** instance, with the task name specified.
1863
1864**System capability**: SystemCapability.Utils.Lang
1865
1866**Atomic service API**: This API can be used in atomic services since API version 13.
1867
1868**Parameters**
1869
1870| Name| Type    | Mandatory| Description                                                        |
1871| ------ | -------- | ---- | ------------------------------------------------------------ |
1872| name   | string   | Yes  | Name of the generic task.                                                  |
1873| func   | (...args: A) => R \| Promise\<R>  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
1874| args   | A | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
1875
1876**Error codes**
1877
1878For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1879
1880| ID| Error Message                               |
1881| -------- | --------------------------------------- |
1882| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
1883| 10200014 | The function is not marked as concurrent. |
1884
1885**Example**
1886
1887```ts
1888@Concurrent
1889function printArgs(args: string): string {
1890  console.info("printArgs: " + args);
1891  return args;
1892}
1893
1894let taskName: string = "taskName";
1895let task: taskpool.Task = new taskpool.GenericsTask<[string], string>(taskName, printArgs, "this is my first Task");
1896let name: string = task.name;
1897```
1898
1899## TaskGroup<sup>10+</sup>
1900
1901Implements a task group, in which tasks are associated with each other and all tasks are executed at a time. If all the tasks are executed normally, an array of task results is returned asynchronously, and the sequence of elements in the array is the same as the sequence of tasks added by calling [addTask](#addtask10-1). If any task fails, the corresponding exception is thrown. A task group can be executed for multiple times, but no task can be added after the task group is executed. Before calling any APIs in **TaskGroup**, you must use [constructor](#constructor10) to create a **TaskGroup** instance.
1902
1903### constructor<sup>10+</sup>
1904
1905constructor()
1906
1907Constructor used to create a **TaskGroup** instance.
1908
1909**System capability**: SystemCapability.Utils.Lang
1910
1911**Atomic service API**: This API can be used in atomic services since API version 11.
1912
1913**Example**
1914
1915```ts
1916let taskGroup = new taskpool.TaskGroup();
1917```
1918
1919### constructor<sup>11+</sup>
1920
1921constructor(name: string)
1922
1923A constructor used to create a **TaskGroup** instance, with the task group name specified.
1924
1925**System capability**: SystemCapability.Utils.Lang
1926
1927**Atomic service API**: This API can be used in atomic services since API version 11.
1928
1929**Parameters**
1930
1931| Name| Type  | Mandatory| Description        |
1932| ------ | ------ | ---- | ------------ |
1933| name   | string | Yes  | Task group name.|
1934
1935**Error codes**
1936
1937For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1938
1939| ID| Error Message|
1940| -------- | -------- |
1941| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1942
1943**Example**
1944
1945```ts
1946let taskGroupName: string = "groupName";
1947let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(taskGroupName);
1948let name: string = taskGroup.name;
1949```
1950
1951### addTask<sup>10+</sup>
1952
1953addTask(func: Function, ...args: Object[]): void
1954
1955Adds the function to be executed to this task group. Before using this API, you must create a **TaskGroup** instance.
1956
1957**System capability**: SystemCapability.Utils.Lang
1958
1959**Atomic service API**: This API can be used in atomic services since API version 11.
1960
1961**Parameters**
1962
1963| Name| Type     | Mandatory| Description                                                                  |
1964| ------ | --------- | ---- | ---------------------------------------------------------------------- |
1965| func   | Function  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
1966| args   | Object[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
1967
1968**Error codes**
1969
1970For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1971
1972| ID| Error Message                                |
1973| -------- | --------------------------------------- |
1974| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1975| 10200014 | The function is not marked as concurrent. |
1976
1977**Example**
1978
1979```ts
1980@Concurrent
1981function printArgs(args: number): number {
1982  console.info("printArgs: " + args);
1983  return args;
1984}
1985
1986let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
1987taskGroup.addTask(printArgs, 100); // 100: test number
1988```
1989
1990### addTask<sup>10+</sup>
1991
1992addTask(task: Task): void
1993
1994Adds a created task to this task group. Before using this API, you must create a **TaskGroup** instance. Tasks in another task group or serial queue, dependent tasks, continuous tasks, tasks that have been executed, and periodic tasks cannot be added to the task group.
1995
1996**System capability**: SystemCapability.Utils.Lang
1997
1998**Atomic service API**: This API can be used in atomic services since API version 11.
1999
2000**Parameters**
2001
2002| Name  | Type                 | Mandatory| Description                                      |
2003| -------- | --------------------- | ---- | ---------------------------------------- |
2004| task     | [Task](#task)         | Yes  | Task to be added to the task group.                 |
2005
2006**Error codes**
2007
2008For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
2009
2010| ID| Error Message                                |
2011| -------- | --------------------------------------- |
2012| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2013| 10200014 | The function is not marked as concurrent. |
2014| 10200051 | The periodic task cannot be executed again.  |
2015
2016**Example**
2017
2018```ts
2019@Concurrent
2020function printArgs(args: number): number {
2021  console.info("printArgs: " + args);
2022  return args;
2023}
2024
2025let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
2026let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
2027taskGroup.addTask(task);
2028```
2029
2030### Attributes
2031
2032**System capability**: SystemCapability.Utils.Lang
2033
2034**Atomic service API**: This API can be used in atomic services since API version 11.
2035
2036| Name| Type  | Readable| Writable| Description                        |
2037| ---- | ------ | ---- | ---- | ---------------------------- |
2038| name<sup>11+</sup> | string | Yes  | Yes  | Name of the task group specified when the task group is created.|
2039
2040## SequenceRunner <sup>11+</sup>
2041
2042Implements a serial queue, in which all tasks are executed in sequence. Before calling any APIs in **SequenceRunner**, you must use [constructor](#constructor11-3) to create a **SequenceRunner** instance.
2043
2044### constructor<sup>11+</sup>
2045
2046constructor(priority?: Priority)
2047
2048A constructor used to create a **SequenceRunner** instance.
2049
2050**System capability**: SystemCapability.Utils.Lang
2051
2052**Atomic service API**: This API can be used in atomic services since API version 11.
2053
2054**Parameters**
2055
2056| Name  | Type                 | Mandatory| Description                                                      |
2057| -------- | --------------------- | ---- | ---------------------------------------------------------- |
2058| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
2059
2060**Error codes**
2061
2062For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
2063
2064| ID| Error Message|
2065| -------- | -------- |
2066| 401 | Parameter error. Possible causes: 1. Incorrect parameter types; 2. Parameter verification failed. |
2067
2068**Example**
2069
2070```ts
2071let runner: taskpool.SequenceRunner = new taskpool.SequenceRunner();
2072```
2073
2074### constructor<sup>12+</sup>
2075
2076constructor(name: string, priority?: Priority)
2077
2078A constructor used to create a **SequenceRunner** instance. This instance represents a global serial queue. If the passed-in name is the same as an existing name, the same serial queue is returned.
2079
2080> **NOTE**
2081>
2082> - The bottom layer uses the singleton mode to ensure that the same instance is obtained when a serial queue with the same name is created.
2083> - The priority of a serial queue cannot be modified.
2084
2085**System capability**: SystemCapability.Utils.Lang
2086
2087**Atomic service API**: This API can be used in atomic services since API version 12.
2088
2089**Parameters**
2090
2091| Name  | Type                 | Mandatory| Description                                                      |
2092| -------- | --------------------- | ---- | ---------------------------------------------------------- |
2093| name     | string                | Yes  | Name of a serial queue.|
2094| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
2095
2096**Error codes**
2097
2098For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
2099
2100| ID| Error Message|
2101| -------- | -------- |
2102| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
2103
2104**Example**
2105
2106```ts
2107let runner:taskpool.SequenceRunner = new taskpool.SequenceRunner("runner1", taskpool.Priority.LOW);
2108```
2109
2110### execute<sup>11+</sup>
2111
2112execute(task: Task): Promise\<Object>
2113
2114Adds a task to the serial queue for execution. Before using this API, you must create a **SequenceRunner** instance. Tasks in another task group or serial queue, dependent tasks, and tasks that have been executed cannot be added to the serial queue.
2115
2116> **NOTE**
2117>
2118> - Tasks that depend others cannot be added to the serial queue.
2119> - The failure or cancellation of a task does not affect the execution of subsequent tasks in the serial queue.
2120
2121**System capability**: SystemCapability.Utils.Lang
2122
2123**Atomic service API**: This API can be used in atomic services since API version 11.
2124
2125**Parameters**
2126
2127| Name| Type         | Mandatory| Description                            |
2128| ------ | ------------- | ---- | -------------------------------- |
2129| task   | [Task](#task) | Yes  | Task to be added to the serial queue.|
2130
2131**Return value**
2132
2133| Type            | Description                             |
2134| ---------------- | --------------------------------- |
2135| Promise\<Object> | Promise used to return the task execution result.|
2136
2137**Error codes**
2138
2139For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
2140
2141| ID| Error Message                                   |
2142| -------- | ------------------------------------------- |
2143| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
2144| 10200006 | An exception occurred during serialization. |
2145| 10200025 | dependent task not allowed.  |
2146| 10200051 | The periodic task cannot be executed again.  |
2147
2148**Example**
2149
2150```ts
2151@Concurrent
2152function additionDelay(delay:number): void {
2153  let start: number = new Date().getTime();
2154  while (new Date().getTime() - start < delay) {
2155    continue;
2156  }
2157}
2158@Concurrent
2159function waitForRunner(finalString: string): string {
2160  return finalString;
2161}
2162async function seqRunner()
2163{
2164  let finalString:string = "";
2165  let task1:taskpool.Task = new taskpool.Task(additionDelay, 3000);
2166  let task2:taskpool.Task = new taskpool.Task(additionDelay, 2000);
2167  let task3:taskpool.Task = new taskpool.Task(additionDelay, 1000);
2168  let task4:taskpool.Task = new taskpool.Task(waitForRunner, finalString);
2169
2170  let runner:taskpool.SequenceRunner = new taskpool.SequenceRunner();
2171  runner.execute(task1).then(() => {
2172    finalString += 'a';
2173    console.info("seqrunner: task1 done.");
2174  });
2175  runner.execute(task2).then(() => {
2176    finalString += 'b';
2177    console.info("seqrunner: task2 done");
2178  });
2179  runner.execute(task3).then(() => {
2180    finalString += 'c';
2181    console.info("seqrunner: task3 done");
2182  });
2183  await runner.execute(task4);
2184  console.info("seqrunner: task4 done, finalString is " + finalString);
2185}
2186```
2187
2188## State<sup>10+</sup>
2189
2190Enumerates the task states. After a task is created and **execute()** is called, the task is placed in the internal queue of the task pool and the state is **WAITING**. When the task is being executed by the worker thread of the task pool, the state changes to **RUNNING**. After the task is executed and the result is returned, the state is reset to **WAITING**. When the task is proactively canceled, the state changes to **CANCELED**.
2191
2192**System capability**: SystemCapability.Utils.Lang
2193
2194**Atomic service API**: This API can be used in atomic services since API version 11.
2195
2196| Name     | Value       | Description         |
2197| --------- | -------- | ------------- |
2198| WAITING   | 1        | The task is waiting.|
2199| RUNNING   | 2        | The task is running.|
2200| CANCELED  | 3        | The task is canceled.|
2201
2202
2203## TaskInfo<sup>10+</sup>
2204
2205Describes the internal information about a task.
2206
2207**System capability**: SystemCapability.Utils.Lang
2208
2209### Attributes
2210
2211**System capability**: SystemCapability.Utils.Lang
2212
2213| Name    | Type               | Readable| Writable| Description                                                          |
2214| -------- | ------------------ | ---- | ---- | ------------------------------------------------------------- |
2215| name<sup>12+</sup> | string             | Yes  | No  | Task name.<br> **Atomic service API**: This API can be used in atomic services since API version 12.                                                   |
2216| taskId   | number             | Yes  | No  | Task ID.<br> **Atomic service API**: This API can be used in atomic services since API version 11.                                                    |
2217| state    | [State](#state10)  | Yes  | No  | Task state.<br> **Atomic service API**: This API can be used in atomic services since API version 11.                                                   |
2218| duration | number             | Yes  | No  | Duration that the task has been executed, in ms. If the return value is **0**, the task is not running. If the return value is empty, no task is running.<br> **Atomic service API**: This API can be used in atomic services since API version 11. |
2219
2220## ThreadInfo<sup>10+</sup>
2221
2222Describes the internal information about a worker thread.
2223
2224**System capability**: SystemCapability.Utils.Lang
2225
2226### Attributes
2227
2228**System capability**: SystemCapability.Utils.Lang
2229
2230**Atomic service API**: This API can be used in atomic services since API version 11.
2231
2232| Name    | Type                   | Readable| Writable| Description                                                     |
2233| -------- | ---------------------- | ---- | ---- | -------------------------------------------------------- |
2234| tid      | number                 | Yes  | No  | ID of the worker thread. If the return value is empty, no task is running.             |
2235| taskIds  | number[]               | Yes  | No  | IDs of tasks running on the calling thread. If the return value is empty, no task is running.  |
2236| priority | [Priority](#priority)  | Yes  | No  | Priority of the calling thread. If the return value is empty, no task is running.             |
2237
2238## TaskPoolInfo<sup>10+</sup>
2239
2240Describes the internal information about a task pool.
2241
2242**System capability**: SystemCapability.Utils.Lang
2243
2244### Attributes
2245
2246**System capability**: SystemCapability.Utils.Lang
2247
2248**Atomic service API**: This API can be used in atomic services since API version 11.
2249
2250| Name         | Type                             | Readable| Writable| Description                 |
2251| ------------- | -------------------------------- | ---- | ---- | -------------------- |
2252| threadInfos   | [ThreadInfo[]](#threadinfo10)    | Yes  | No  | Internal information about the worker threads.  |
2253| taskInfos     | [TaskInfo[]](#taskinfo10)        | Yes  | No  | Internal information about the tasks.      |
2254
2255
2256## Additional Information
2257
2258### Sequenceable Data Types
2259The following sequenceable data types are supported: [common object](../../arkts-utils/normal-object.md), [ArrayBuffer object](../../arkts-utils/arraybuffer-object.md), [SharedArrayBuffer object](../../arkts-utils/shared-arraybuffer-object.md), [Transferable object (NativeBinding object)](../../arkts-utils/transferabled-object.md), and [Sendable object](../../arkts-utils/arkts-sendable.md).
2260
2261### Using the Task Pool in Simple Mode
2262
2263**Example 1**
2264
2265```ts
2266// Common functions are supported, and variables passed in by input parameters are also supported.
2267@Concurrent
2268function printArgs(args: string): string {
2269  console.info("func: " + args);
2270  return args;
2271}
2272
2273async function taskpoolExecute(): Promise<void> {
2274  // taskpool.execute(task)
2275  let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
2276  console.info("taskpool.execute(task) result: " + await taskpool.execute(task));
2277  // taskpool.execute(function)
2278  console.info("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
2279}
2280
2281taskpoolExecute();
2282```
2283
2284**Example 2**
2285
2286```ts
2287// b.ets
2288export let c: string = "hello";
2289```
2290<!--code_no_check-->
2291```ts
2292// Reference an imported variable.
2293// a.ets (in the same directory as b.ets)
2294import { c } from "./b";
2295
2296@Concurrent
2297function printArgs(a: string): string {
2298  console.info(a);
2299  console.info(c);
2300  return a;
2301}
2302
2303async function taskpoolExecute(): Promise<void> {
2304  // taskpool.execute(task)
2305  let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
2306  console.info("taskpool.execute(task) result: " + await taskpool.execute(task));
2307
2308  // taskpool.execute(function)
2309  console.info("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
2310}
2311
2312taskpoolExecute();
2313```
2314
2315**Example 3**
2316
2317```ts
2318// The async functions are supported.
2319@Concurrent
2320async function delayExecute(): Promise<Object> {
2321  let ret = await Promise.all<Object>([
2322    new Promise<Object>(resolve => setTimeout(resolve, 1000, "resolved"))
2323  ]);
2324  return ret;
2325}
2326
2327async function taskpoolExecute(): Promise<void> {
2328  taskpool.execute(delayExecute).then((result: Object) => {
2329    console.info("taskPoolTest task result: " + result);
2330  }).catch((err: string) => {
2331    console.error("taskpool test occur error: " + err);
2332  });
2333}
2334
2335taskpoolExecute();
2336```
2337
2338**Example 4**
2339
2340```ts
2341// c.ets
2342import { taskpool } from '@kit.ArkTS';
2343
2344@Concurrent
2345function strSort(inPutArr: Array<string>): Array<string> {
2346  let newArr = inPutArr.sort();
2347  return newArr;
2348}
2349
2350export async function func1(): Promise<void> {
2351  console.info("taskpoolTest start");
2352  let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
2353  let task: taskpool.Task = new taskpool.Task(strSort, strArray);
2354  console.info("func1 result:" + await taskpool.execute(task));
2355}
2356
2357export async function func2(): Promise<void> {
2358  console.info("taskpoolTest2 start");
2359  let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
2360  taskpool.execute(strSort, strArray).then((result: Object) => {
2361    console.info("func2 result: " + result);
2362  }).catch((err: string) => {
2363    console.error("taskpool test occur error: " + err);
2364  });
2365}
2366```
2367<!--code_no_check-->
2368```ts
2369// index.ets
2370import { func1, func2 } from "./c";
2371
2372func1();
2373func2();
2374```
2375
2376**Example 5**
2377
2378```ts
2379// Success in canceling a task
2380@Concurrent
2381function inspectStatus(arg: number): number {
2382  // Check whether the task has been canceled and respond accordingly.
2383  if (taskpool.Task.isCanceled()) {
2384    console.info("task has been canceled before 2s sleep.");
2385    return arg + 2;
2386  }
2387  // 2s sleep
2388  let t: number = Date.now();
2389  while (Date.now() - t < 2000) {
2390    continue;
2391  }
2392  // Check again whether the task has been canceled and respond accordingly.
2393  if (taskpool.Task.isCanceled()) {
2394    console.info("task has been canceled after 2s sleep.");
2395    return arg + 3;
2396  }
2397  return arg + 1;
2398}
2399
2400async function taskpoolCancel(): Promise<void> {
2401  let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
2402  taskpool.execute(task).then((res: Object) => {
2403    console.info("taskpool test result: " + res);
2404  }).catch((err: string) => {
2405    console.error("taskpool test occur error: " + err);
2406  });
2407  // Cancel the task 1s later.
2408  setTimeout(() => {
2409    try {
2410      taskpool.cancel(task);
2411    } catch (e) {
2412      console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
2413    }
2414  }, 1000);
2415}
2416
2417taskpoolCancel();
2418```
2419
2420**Example 6**
2421
2422```ts
2423// Failure to cancel a task that has been executed
2424@Concurrent
2425function inspectStatus(arg: number): number {
2426  // Check whether the task has been canceled and respond accordingly.
2427  if (taskpool.Task.isCanceled()) {
2428    return arg + 2;
2429  }
2430  // Wait for 2s.
2431  let t: number = Date.now();
2432  while (Date.now() - t < 500) {
2433    continue;
2434  }
2435  // Check again whether the task has been canceled and respond accordingly.
2436  if (taskpool.Task.isCanceled()) {
2437    return arg + 3;
2438  }
2439  return arg + 1;
2440}
2441
2442async function taskpoolCancel(): Promise<void> {
2443  let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
2444  taskpool.execute(task).then((res: Object) => {
2445    console.info("taskpool test result: " + res);
2446  }).catch((err: string) => {
2447    console.error("taskpool test occur error: " + err);
2448  });
2449
2450  setTimeout(() => {
2451    try {
2452      taskpool.cancel(task); // The task has been executed and fails to be canceled.
2453    } catch (e) {
2454      console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
2455    }
2456  }, 3000); // Wait for 3s to ensure that the task has been executed.
2457}
2458
2459taskpoolCancel();
2460```
2461
2462**Example 7**
2463
2464```ts
2465// Success of canceling a task group to be executed
2466@Concurrent
2467function printArgs(args: number): number {
2468  let t: number = Date.now();
2469  while (Date.now() - t < 1000) {
2470    continue;
2471  }
2472  console.info("printArgs: " + args);
2473  return args;
2474}
2475
2476async function taskpoolGroupCancelTest(): Promise<void> {
2477  let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
2478  taskGroup1.addTask(printArgs, 10); // 10: test number
2479  taskGroup1.addTask(printArgs, 20); // 20: test number
2480  taskGroup1.addTask(printArgs, 30); // 30: test number
2481  let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
2482  let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
2483  let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
2484  let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
2485  taskGroup2.addTask(task1);
2486  taskGroup2.addTask(task2);
2487  taskGroup2.addTask(task3);
2488  taskpool.execute(taskGroup1).then((res: Array<Object>) => {
2489    console.info("taskpool execute res is:" + res);
2490  }).catch((e: string) => {
2491    console.error("taskpool execute error is:" + e);
2492  });
2493  taskpool.execute(taskGroup2).then((res: Array<Object>) => {
2494    console.info("taskpool execute res is:" + res);
2495  }).catch((e: string) => {
2496    console.error("taskpool execute error is:" + e);
2497  });
2498
2499  try {
2500    taskpool.cancel(taskGroup2);
2501  } catch (e) {
2502    console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
2503  }
2504}
2505
2506taskpoolGroupCancelTest()
2507```
2508
2509**Example 8**
2510
2511```ts
2512// Create and execute 100 tasks with different priorities, and view their information.
2513@Concurrent
2514function delay(): void {
2515  let start: number = new Date().getTime();
2516  while (new Date().getTime() - start < 500) {
2517    continue;
2518  }
2519}
2520
2521let highCount: number = 0;
2522let mediumCount: number = 0;
2523let lowCount: number = 0;
2524let allCount: number = 100;
2525for (let i = 0; i < allCount; i++) {
2526  let task1: taskpool.Task = new taskpool.Task(delay);
2527  let task2: taskpool.Task = new taskpool.Task(delay);
2528  let task3: taskpool.Task = new taskpool.Task(delay);
2529  taskpool.execute(task1, taskpool.Priority.LOW).then(() => {
2530    lowCount++;
2531  }).catch((e: string) => {
2532    console.error("low task error: " + e);
2533  })
2534  taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => {
2535    mediumCount++;
2536  }).catch((e: string) => {
2537    console.error("medium task error: " + e);
2538  })
2539  taskpool.execute(task3, taskpool.Priority.HIGH).then(() => {
2540    highCount++;
2541  }).catch((e: string) => {
2542    console.error("high task error: " + e);
2543  })
2544}
2545let start: number = new Date().getTime();
2546while (new Date().getTime() - start < 1000) {
2547  continue;
2548}
2549let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
2550let tid: number = 0;
2551let taskIds: Array<number> = [];
2552let priority: number = 0;
2553let taskId: number = 0;
2554let state: number = 0;
2555let duration: number = 0;
2556let name: string = "";
2557let threadIS = Array.from(taskpoolInfo.threadInfos)
2558for (let threadInfo of threadIS) {
2559  tid = threadInfo.tid;
2560  if (threadInfo.taskIds != undefined && threadInfo.priority != undefined) {
2561    taskIds.length = threadInfo.taskIds.length;
2562    priority = threadInfo.priority;
2563  }
2564  console.info("taskpool---tid is:" + tid + ", taskIds is:" + taskIds + ", priority is:" + priority);
2565}
2566let taskIS = Array.from(taskpoolInfo.taskInfos)
2567for (let taskInfo of taskIS) {
2568  taskId = taskInfo.taskId;
2569  state = taskInfo.state;
2570  if (taskInfo.duration != undefined) {
2571    duration = taskInfo.duration;
2572    name = taskInfo.name;
2573  }
2574  console.info("taskpool---taskId is:" + taskId + ", state is:" + state + ", duration is:" + duration + ", name is:" + name);
2575}
2576```
2577