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