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