TaskPool 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 thread lifecycle. You can use the task pool APIs to create background tasks (Task), execute or cancel tasks, and so on. Theoretically, the number of tasks that can be created using the task pool APIs is unlimited. However, due to memory limits, it is not recommended to create a large number of tasks without restriction. In addition, it is not recommended to perform blocking operations in tasks, especially indefinite blocking operations, because blocking operations occupy worker threads and affect the scheduling of other tasks and application performance.
You 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.
If 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.
For details about the error codes returned by TaskPool APIs, see Utils Error Codes.
For details about the precautions for using TaskPool, see Precautions for TaskPool.
The following concepts are used in this topic:
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.
execute(func: Function, ...args: Object[]): Promise<Object>
Places 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. This API uses a promise to return the result.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| func | Function | Yes | Function to execute. It must be decorated by @Concurrent. For details about the supported return value types of the function, see Sequenceable Data Types. |
| args | Object[] | No | Arguments of the task execution function. For details about the supported parameter types, see Sequenceable Data Types. The default value is undefined. |
Return value
| Type | Description |
|---|---|
| Promise<Object> | Promise used to return an object that carries the function execution result. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200003 | Worker initialization failed. Applicable version: 9-11 |
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not marked as concurrent. |
Example
@Concurrent
function printArgs(args: number): number {
console.info("printArgs: " + args);
return args;
}
taskpool.execute(printArgs, 100).then((value: Object) => { // 100: test number
console.info("taskpool result: " + value);
}); execute<A extends Array<Object>, R>(func: (...args: A) => R | Promise<R>, ...args: A): Promise<R>
After the parameter types and return type of the concurrent function are verified, the function is added to the task queue of the task pool. In the current execution mode, task cancellation is not supported. A Promise is used to return the result asynchronously.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 13.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| func | (...args: A) => R | Promise<R> | Yes | Function to execute. It must be decorated by @Concurrent. For the supported return value types, see Sequenceable Data Types. |
| args | A | No | Input parameters of the task function. For the supported parameter types, see Sequenceable Data Types. The default value is undefined. |
Return value
| Type | Description |
|---|---|
| Promise<R> | Promise used to return an object that carries the function execution result. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not marked as concurrent. |
Example
@Concurrent
function printArgs(args: number): number {
console.info("printArgs: " + args);
return args;
}
@Concurrent
function testWithThreeParams(a: number, b: string, c: number): string {
return b;
}
@Concurrent
function testWithArray(args: [number, string]): string {
return "success";
}
taskpool.execute<[number], number>(printArgs, 100).then((value: number) => { // 100: test number
console.info("taskpool result: " + value); // "taskpool result: 100"
});
taskpool.execute<[number, string, number], string>(testWithThreeParams, 100, "test", 100).then((value: string) => {
console.info("taskpool result: " + value); // "taskpool result: test"
});
taskpool.execute<[[number, string]], string>(testWithArray, [100, "test"]).then((value: string) => {
console.info("taskpool result: " + value); // "taskpool result: success"
}); execute(task: Task, priority?: Priority): Promise<Object>
Places a task in the internal queue of the task pool. The task will not be executed immediately; instead, it waits to be distributed to a worker thread for execution. In the current mode, you can set the task priority and cancel the task through cancel. A Promise is used to return the result asynchronously.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| task | Task | Yes | Task to be executed. |
| priority | Priority | No | Priority of the task waiting for execution. The default value is taskpool.Priority.MEDIUM. |
Return value
| Type | Description |
|---|---|
| Promise<Object> | Promise used to return an object that carries the function execution result. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200003 | Worker initialization failed. Applicable version: 9-17 |
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not marked as concurrent. |
| 10200051 | The periodic task cannot be executed again. Applicable version: 12+ |
| 10200057 | The task cannot be executed by two APIs. Applicable version: 18+ |
Example
@Concurrent
function printArgs(args: number): number {
console.info("printArgs: " + args);
return args;
}
let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
taskpool.execute(task1, taskpool.Priority.LOW).then((value: Object) => {
console.info("taskpool result1: " + value);
});
taskpool.execute(task2, taskpool.Priority.MEDIUM).then((value: Object) => {
console.info("taskpool result2: " + value);
});
taskpool.execute(task3, taskpool.Priority.HIGH).then((value: Object) => {
console.info("taskpool result3: " + value);
}); execute(task: Task, configs: Configs): Promise<Object>
Adds the created task to the internal task queue of taskpool. The task is not executed immediately but waits to be distributed to a worker thread for execution. The current mode supports setting the task priority, setting the timeout, and canceling the task through cancel. This API uses a promise to return the result asynchronously.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 24.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| task | Task | Yes | Task to be executed in the task pool. |
| configs | Configs | Yes | This parameter can be used to set the timeout and task priority. |
Return value
| Type | Description |
|---|---|
| Promise<Object> | Promise object used to return the execution result of the task function. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not marked as concurrent. |
| 10200051 | The periodic task cannot be executed again. |
| 10200057 | The task cannot be executed by two APIs. |
| 10200058 | Task timed out. |
Example
@Concurrent
function printArgs(args: number, time: number): number {
let start = Date.now();
while (Date.now() - start < time) {
continue;
}
return args;
}
let task: taskpool.Task = new taskpool.Task(printArgs, 100, 1000);
let config: taskpool.Configs = { timeout: 500, priority: taskpool.Priority.HIGH };
taskpool.execute(task, config).catch((e: BusinessError) => {
// Failed to execute task. Code: 10200058, message: Task timed out.
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
})
try {
taskpool.execute(task, { timeout: 500 });
} catch (e) {
// Failed to execute task. Code: 10200057, message: The task cannot be executed by two APIs, the timeout task cannot be executed again.
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
} execute<A extends Array<Object>, R>(task: GenericsTask<A, R>, priority?: Priority): Promise<R>
Adds the created generic task to the internal task queue of taskpool and verifies the parameter type and return value type of the task. This API uses a promise to return the result asynchronously.
The type verification of the execute task is associated with the construction type of GenericsTask. The parameter type and return value type must be consistent with those specified when new GenericsTask is created.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 13.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| task | GenericsTask<A, R> | Yes | Generic task to be executed in the task pool. |
| priority | Priority | No | Priority of the task to be executed. The default value is taskpool.Priority.MEDIUM. |
Return value
| Type | Description |
|---|---|
| Promise<R> | Promise used to return an object that carries the function execution result. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not marked as concurrent. |
| 10200051 | The periodic task cannot be executed again. |
| 10200057 | The task cannot be executed by two APIs. Applicable version: 18+ |
Example
@Concurrent
function printArgs(args: number): number {
console.info("printArgs: " + args);
return args;
}
let task1: taskpool.Task = new taskpool.GenericsTask<[number], number>(printArgs, 100); // 100: test number
let task2: taskpool.Task = new taskpool.GenericsTask<[number], number>(printArgs, 200); // 200: test number
let task3: taskpool.Task = new taskpool.GenericsTask<[number], number>(printArgs, 300); // 300: test number
taskpool.execute<[number], number>(task1, taskpool.Priority.LOW).then((value: number) => {
console.info("taskpool result1: " + value);
});
taskpool.execute<[number], number>(task2, taskpool.Priority.MEDIUM).then((value: number) => {
console.info("taskpool result2: " + value);
});
taskpool.execute<[number], number>(task3, taskpool.Priority.HIGH).then((value: number) => {
console.info("taskpool result3: " + value);
}); execute<A extends Array<Object>, R>(task: GenericsTask<A, R>, configs: Configs): Promise<R>
Places the created generic task into the internal task queue of taskpool and uses a Promise for asynchronous callback.
The type check of the execute task is associated with the construction type of GenericsTask. The parameter type and return value type must be consistent with the types specified when creating the GenericsTask instance.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 24.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| task | GenericsTask<A, R> | Yes | Generic task to be executed in the task pool. |
| configs | Configs | Yes | This parameter can be used to set the timeout and task priority. |
Return value
| Type | Description |
|---|---|
| Promise<R> | Promise object, which returns the execution result of the task function. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not marked as concurrent. |
| 10200051 | The periodic task cannot be executed again. |
| 10200057 | The task cannot be executed by two APIs. |
| 10200058 | Task timed out. |
Example
@Concurrent
function printArgs(args: number, time: number): number {
let start = Date.now();
while (Date.now() - start < time) {
continue;
}
return args;
}
let task: taskpool.Task = new taskpool.GenericsTask<[number, number], number>(printArgs, 100, 1000);
let config: taskpool.Configs = { timeout: 500, priority: taskpool.Priority.MEDIUM };
taskpool.execute<[number, number], number>(task, config).catch((e: BusinessError) => {
// Failed to execute task. Code: 10200058, message: Task timed out.
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
})
try {
taskpool.execute<[number, number], number>(task, { timeout: 500 });
} catch (e) {
// Failed to execute task. Code: 10200057, message: The task cannot be executed by two APIs, the timeout task cannot be executed again.
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
} execute(group: TaskGroup, priority?: Priority): Promise<Object[]>
Places 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 mode is applicable to the execution of associated tasks. This API uses a promise to return the result.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| group | TaskGroup | Yes | Task group to be executed. |
| priority | Priority | No | Priority of the task group. The default value is taskpool.Priority.MEDIUM. |
Return value
| Type | Description |
|---|---|
| Promise<Object[]> | Promise used to return an object array that carries the function execution result. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. |
| 10200059 | TaskGroup cannot be re-executed. Applicable version: 24+ |
Example
@Concurrent
function printArgs(args: number): number {
console.info("printArgs: " + args);
return args;
}
let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
taskGroup1.addTask(printArgs, 20); // 20: test number
taskGroup1.addTask(printArgs, 30); // 30: test number
let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
taskGroup2.addTask(task1);
taskGroup2.addTask(task2);
taskGroup2.addTask(task3);
taskpool.execute(taskGroup1).then((res: Array<Object>) => {
console.info("Succeeded in executing task, res is:" + res);
});
taskpool.execute(taskGroup2).then((res: Array<Object>) => {
console.info("Succeeded in executing task, res is:" + res);
}); execute(group: TaskGroup, configs: Configs): Promise<Object[]>
Places the created task group into the internal task queue of the taskpool. Tasks in the task group are not executed immediately but wait to be dispatched to worker threads for execution. After all tasks in the task group are executed, the result array is returned as a whole. This mode is suitable for executing associated tasks. Promise is used to return the result asynchronously.
The configs parameter can specify the timeout period and priority for task group execution. If the specified timeout period expires before the task group is completed, a task group timeout exception is thrown.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 24.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| group | TaskGroup | Yes | Task group to be executed in the task pool. |
| configs | Configs | Yes | This parameter can set the timeout period and task priority. |
Return value
| Type | Description |
|---|---|
| Promise<Object[]> | Array of Promise objects, which returns the execution result of the task function. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. |
| 10200059 | TaskGroup cannot be re-executed. |
| 10200070 | TaskGroup timed out. |
Example
@Concurrent
function printArgs(args: number, time: number): number {
let start = Date.now();
while (Date.now() - start < time) {
continue;
}
return args;
}
let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup.addTask(printArgs, 10, 1000);
let config: taskpool.Configs = {timeout: 500, priority: taskpool.Priority.HIGH};
taskpool.execute(taskGroup, config).catch((e:BusinessError) => {
// Failed to execute task. Code: 10200070, message: TaskGroup timed out.
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
})
try {
taskpool.execute(taskGroup, config);
} catch (e) {
// Failed to execute task. Code: 10200059, message: TaskGroup cannot be re-executed, taskGroup has already set timeout.
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
} executeDelayed(delayTime: number, task: Task, priority?: Priority): Promise<Object>
Executes a task with a delay. In this execution mode, you can set the task priority and call cancel() to cancel the task. Promise is used to return the result asynchronously.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| delayTime | number | Yes | Delay time. Unit: ms. The value of delayTime must be greater than or equal to 0. |
| task | Task | Yes | Task to be executed with a delay. |
| priority | Priority | No | Priority of the task. The default value is taskpool.Priority.MEDIUM. |
Return value
| Type | Description |
|---|---|
| Promise<Object> | Promise used to return an object that carries the function execution result. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. Applicable version: 12+ |
| 10200014 | The function is not marked as concurrent. Applicable version: 12+ |
| 10200028 | The delayTime is less than zero. |
| 10200051 | The periodic task cannot be executed again. Applicable version: 12+ |
| 10200057 | The task cannot be executed by two APIs. Applicable version: 18+ |
Example
// import BusinessError
import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
function printArgs(args: number): void {
console.info("printArgs: " + args);
}
let t: number = Date.now();
console.info("taskpool start time is: " + t);
let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
taskpool.executeDelayed(1000, task).then(() => { // 1000: delayTime is 1000ms
console.info('Succeeded in executing task');
}).catch((e: BusinessError) => {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
}) executeDelayed<A extends Array<Object>, R>(delayTime: number, task: GenericsTask<A, R>, priority?: Priority): Promise<R>
Executes a generic task with a delay. Promise is used to return the result asynchronously.
The type check of the executeDelayed task is associated with the construction type of GenericsTask. The parameter type and return value type must be consistent with the types specified when creating the GenericsTask instance.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 13.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| delayTime | number | Yes | Delay time, in ms. The value of delayTime must be greater than or equal to 0. |
| task | GenericsTask<A, R> | Yes | Generic task to be executed after the delay. |
| priority | Priority | No | Priority of the task. The default value is taskpool.Priority.MEDIUM. |
Return value
| Type | Description |
|---|---|
| Promise<R> | Promise used to return an object that carries the function execution result. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200028 | The delayTime is less than zero. |
| 10200051 | The periodic task cannot be executed again. |
| 10200057 | The task cannot be executed by two APIs. Applicable version: 18+ |
Example
// import BusinessError
import { BusinessError } from '@kit.BasicServicesKit'
@Concurrent
function printArgs(args: number): string {
console.info("printArgs: " + args);
return "success";
}
let task: taskpool.Task = new taskpool.GenericsTask<[number], string>(printArgs, 100); // 100: test number
taskpool.executeDelayed<[number], string>(1000, task).then((res: string) => { // 1000: delayTime is 1000ms
console.info('Succeeded in executing task');
}).catch((e: BusinessError) => {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
}) executePeriodically(period: number, task: Task, priority?: Priority): void
A periodic task is executed once every period. The current execution mode supports setting the task priority, and the task can be canceled by calling cancel.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| period | number | Yes | Period duration. Unit: ms. The value of period must be greater than or equal to 0. |
| task | Task | Yes | Task to be executed. |
| priority | Priority | No | Priority of the task. The default value is taskpool.Priority.MEDIUM. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not marked as concurrent. |
| 10200028 | The period is less than zero. |
| 10200050 | The concurrent task has been executed and cannot be executed periodically. |
| 10200057 | The task cannot be executed by two APIs. Applicable version: 18+ |
Example
@Concurrent
function printArgs(args: number): void {
console.info("printArgs: " + args);
}
@Concurrent
function testExecutePeriodically(args: number): void {
let t = Date.now();
while ((Date.now() - t) < args) {
continue;
}
taskpool.Task.sendData(args); // Send a message to the host thread.
}
function printResult(data: number): void {
console.info("taskpool: data is: " + data);
}
function taskpoolTest() {
try {
let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
taskpool.executePeriodically(1000, task); // 1000: period is 1000ms
} catch (e) {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
}
try {
let periodicTask: taskpool.Task = new taskpool.Task(testExecutePeriodically, 200); // 200: test number
periodicTask.onReceiveData(printResult);
taskpool.executePeriodically(1000, periodicTask); // 1000: period is 1000ms
} catch (e) {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
}
}
taskpoolTest(); executePeriodically<A extends Array<Object>, R>(period: number, task: GenericsTask<A, R>, priority?: Priority): void
Periodically executes a generic task, once every period.
The type check of the executePeriodically task is associated with the construction type of GenericsTask. The parameter type and return value type must be consistent with the types specified when creating the GenericsTask instance.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 13.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| period | number | Yes | Period duration. Unit: ms. The value of period must be greater than or equal to 0. |
| task | GenericsTask<A, R> | Yes | Generic task to be executed periodically. |
| priority | Priority | No | Priority of the task. The default value is taskpool.Priority.MEDIUM. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not marked as concurrent. |
| 10200028 | The period is less than zero. |
| 10200050 | The concurrent task has been executed and cannot be executed periodically. |
| 10200057 | The task cannot be executed by two APIs. Applicable version: 18+ |
Example
@Concurrent
function printArgs(args: number): void {
console.info("printArgs: " + args);
}
@Concurrent
function testExecutePeriodically(args: number): void {
let t = Date.now();
while ((Date.now() - t) < args) {
continue;
}
taskpool.Task.sendData(args); // Send a message to the host thread.
}
function printResult(data: number): void {
console.info("taskpool: data is: " + data);
}
function taskpoolTest() {
try {
let task: taskpool.Task = new taskpool.GenericsTask<[number], void>(printArgs, 100); // 100: test number
taskpool.executePeriodically<[number], void>(1000, task); // 1000: period is 1000ms
} catch (e) {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
}
try {
let periodicTask: taskpool.Task = new taskpool.GenericsTask<[number], void>(testExecutePeriodically, 200); // 200: test number
periodicTask.onReceiveData(printResult);
taskpool.executePeriodically<[number], void>(1000, periodicTask); // 1000: period is 1000ms
} catch (e) {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
}
}
taskpoolTest(); cancel(task: Task): void
Cancels a task in the task pool.
Starting from API version 20, after performing a cancel operation, you can use the generic type BusinessError<taskpool.TaskResult> in the catch branch to obtain the exception information thrown by the task or the final execution result.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| task | Task | Yes | Task to cancel. |
Error codes
For details about the error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200015 | The task to cancel does not exist. |
| 10200016 | The task to cancel is being executed. Applicable version: 9-17 |
| 10200055 | The asyncRunner task has been canceled. Applicable version: 18+ |
Example of canceling an ongoing task
import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
function inspectStatus(arg: number): number {
// Check whether the task has been canceled and respond accordingly.
if (taskpool.Task.isCanceled()) {
console.info("task has been canceled before 2s sleep.");
return arg + 2;
}
// 2s sleep
let t: number = Date.now();
while (Date.now() - t < 2000) {
continue;
}
// Check again whether the task has been canceled and respond accordingly.
if (taskpool.Task.isCanceled()) {
console.info("task has been canceled after 2s sleep.");
return arg + 3;
}
return arg + 1;
}
function concurrentFunc() {
let task1: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
let task2: taskpool.Task = new taskpool.Task(inspectStatus, 200); // 200: test number
let task3: taskpool.Task = new taskpool.Task(inspectStatus, 300); // 300: test number
let task4: taskpool.Task = new taskpool.Task(inspectStatus, 400); // 400: test number
let task5: taskpool.Task = new taskpool.Task(inspectStatus, 500); // 500: test number
let task6: taskpool.Task = new taskpool.Task(inspectStatus, 600); // 600: test number
taskpool.execute(task1).then((res: Object) => {
console.info(`Succeeded in executing task. result: ` + res);
}).catch((err: BusinessError) => {
console.error(`Failed to execute task. Code: ${err.code}, message: ${err.message}`);
});
taskpool.execute(task2);
taskpool.execute(task3);
taskpool.execute(task4);
taskpool.execute(task5);
taskpool.execute(task6);
// Cancel the task 1s later.
setTimeout(() => {
try {
taskpool.cancel(task1);
} catch (e) {
console.error(`Failed to cancel task. Code: ${e.code}, message: ${e.message}`);
}
}, 1000);
}
concurrentFunc(); cancel(group: TaskGroup): void
Cancels a task group in the task pool. If not all tasks in the task group have finished executing, the execution result of the entire task group returns undefined.
Starting from API version 20, after performing a cancel operation, you can use the generic type BusinessError<taskpool.TaskResult> in the catch branch to obtain the exception information thrown by the task or the final execution result.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| group | TaskGroup | Yes | Task group to cancel. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200018 | The task group to cancel does not exist. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
function printArgs(args: number): number {
let t: number = Date.now();
while (Date.now() - t < 2000) {
continue;
}
console.info("printArgs: " + args);
return args;
}
function concurrentFunc() {
let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup2.addTask(printArgs, 100); // 100: test number
taskpool.execute(taskGroup1).then((res: Array<Object>) => {
console.info(`Succeeded in executing task. res is: ` + res);
});
taskpool.execute(taskGroup2).then((res: Array<Object>) => {
console.info(`Succeeded in executing task. res is: ` + res);
}).catch((err: BusinessError) => {
console.error(`Failed to execute task. Code: ${err.code}, message: ${err.message}`);
});
setTimeout(() => {
try {
taskpool.cancel(taskGroup2);
} catch (e) {
console.error(`Failed to cancel task. Code: ${e.code}, message: ${e.message}`);
}
}, 1000);
}
concurrentFunc(); cancel(taskId: number): void
Cancels a task in the task pool by task ID.
Starting from API version 20, after performing a cancel operation, you can use the generic type BusinessError<taskpool.TaskResult> in the catch branch to obtain the exception information thrown by the task or the final execution result.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 18.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| taskId | number | Yes | ID of the task to cancel. |
Error codes
For details about the error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200015 | The task to cancel does not exist. |
| 10200055 | The asyncRunner task has been canceled. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
function printArgs(args: number): number {
let t: number = Date.now();
while (Date.now() - t < 2000) {
continue;
}
if (taskpool.Task.isCanceled()) {
console.info("task has been canceled after 2s sleep.");
return args + 1;
}
console.info("printArgs: " + args);
return args;
}
@Concurrent
function cancelFunction(taskId: number) {
try {
taskpool.cancel(taskId);
} catch (e) {
console.error(`Failed to cancel task. Code: ${e.code}, message: ${e.message}`);
}
}
function concurrentFunc() {
let task = new taskpool.Task(printArgs, 100); // 100: test number
taskpool.execute(task).catch((err: BusinessError) => {
console.error(`Failed to execute task. Code: ${err.code}, message: ${err.message}`);
});
setTimeout(() => {
let cancelTask = new taskpool.Task(cancelFunction, task.taskId);
taskpool.execute(cancelTask);
}, 1000);
}
concurrentFunc(); terminateTask(longTask: LongTask): void
Terminates a long-running task in the task pool. Call this API after the long-running task finishes execution. After termination, the thread executing the long-running task may be reclaimed.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| longTask | LongTask | Yes | Long-running task to be terminated. |
Example
@Concurrent
function longTask(arg: number): number {
let t: number = Date.now();
while (Date.now() - t < arg) {
continue;
}
console.info("longTask has been executed.");
return arg;
}
function concurrentFunc() {
let task1: taskpool.LongTask = new taskpool.LongTask(longTask, 1000); // 1000: sleep time
taskpool.execute(task1).then((res: Object) => {
taskpool.terminateTask(task1);
console.info("taskpool longTask result: " + res);
});
}
concurrentFunc(); isConcurrent(func: Function): boolean
Checks whether a function is a concurrent function.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| func | Function | Yes | Function to check. |
Return value
| Type | Description |
|---|---|
| boolean | Check result. The value true is returned if the function is a concurrent function, that is, a function decorated with @Concurrent; otherwise, false is returned. |
Example
@Concurrent
function emptyFunc(): void {}
let result: boolean = taskpool.isConcurrent(emptyFunc);
console.info("result is: " + result); getTaskPoolInfo(): TaskPoolInfo
Obtains the thread information and task information of the task pool.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Return value
| Type | Description |
|---|---|
| TaskPoolInfo | Internal information about the task pool. |
Example
let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
getTask(taskId: number, taskName?: string): Task | undefined
Obtains the corresponding task instance by task ID, or by task ID and task name.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 22.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| taskId | number | Yes | Task ID. |
| taskName | string | No | Task name. The default value is undefined. |
Return value
| Type | Description |
|---|---|
| Task | undefined | Task instance. If an exception occurs, undefined is returned. For details, see the preceding description. |
Example
import { taskpool } from '@kit.ArkTS';
@Concurrent
function addNum(num1: number, num2: number) {
return num1 + num2;
}
function checkTask() {
try {
taskpool.getTask(null);
} catch (e) {
console.error("error:" + e);
// error:BusinessError: Parameter error. The input parameters are invalid, the type of the first param must be number.
}
let task1:taskpool.Task = new taskpool.Task("addNum", addNum, 1, 2);
let task2:taskpool.Task | undefined = taskpool.getTask(task1.taskId, "addNum"); // task2 is not undefined
let task3:taskpool.Task | undefined = taskpool.getTask(task1.taskId, "add"); // task3 is undefined
let task4:taskpool.Task | undefined = taskpool.getTask(0); // task4 is undefined
}
function dealTask() {
let task1:taskpool.Task = new taskpool.Task(addNum, 1, 2);
let task2:taskpool.Task | undefined = taskpool.getTask(task1.taskId);
if (task2 === undefined) {
return;
}
taskpool.execute(task2).then((result) => {
console.info("task2 result: " + result); // task2 result: 3
})
} Indicates the priority of the created task (Task) during execution. The worker thread priority is updated along with the task priority. For the mapping relationship, see QoS Level Definition.
System capability: SystemCapability.Utils.Lang
| Name | Value | Description |
|---|---|---|
| HIGH | 0 | The task has a high priority. Atomic service API: This API can be used in atomic services since API version 11. |
| MEDIUM | 1 | The task has a medium priority. Atomic service API: This API can be used in atomic services since API version 11. |
| LOW | 2 | The task has a low priority. Atomic service API: This API can be used in atomic services since API version 11. |
| IDLE12+ | 3 | The task is a background task. Atomic service API: This API can be used in atomic services since API version 12. |
Example
@Concurrent
function printArgs(args: number): number {
let t: number = Date.now();
while (Date.now() - t < 1000) { // 1000: delay 1s
continue;
}
console.info("printArgs: " + args);
return args;
}
let allCount = 100; // 100: test number
let taskArray: Array<taskpool.Task> = [];
// Create 400 tasks and add them to taskArray.
for (let i: number = 0; i < allCount; i++) {
let task1: taskpool.Task = new taskpool.Task(printArgs, i);
taskArray.push(task1);
let task2: taskpool.Task = new taskpool.Task(printArgs, i * 10); // 10: test number
taskArray.push(task2);
let task3: taskpool.Task = new taskpool.Task(printArgs, i * 100); // 100: test number
taskArray.push(task3);
let task4: taskpool.Task = new taskpool.Task(printArgs, i * 1000); // 1000: test number
taskArray.push(task4);
}
// Obtain different tasks from taskArray and specify different priorities for execution.
for (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.
taskpool.execute(taskArray[i], taskpool.Priority.HIGH);
taskpool.execute(taskArray[i + 1], taskpool.Priority.LOW);
taskpool.execute(taskArray[i + 2], taskpool.Priority.MEDIUM);
taskpool.execute(taskArray[i + 3], taskpool.Priority.IDLE);
} Before calling any API in Task, you must use the constructor to create a Task object. A task can be executed multiple times, placed in a task group, serial queue, or asynchronous queue for execution, and supports adding dependencies.
System capability: SystemCapability.Utils.Lang
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| function | Function | No | No | Function to be executed. It must be decorated by the @Concurrent decorator. For the supported return value types of the function, see Sequenceable Data Types. Atomic service API: Since API version 11, this API is supported in atomic services. |
| arguments | Object[] | No | Yes | Parameters required for the function when creating a task. For the supported parameter types, see Sequenceable Data Types. The default value is undefined. Atomic service API: Since API version 11, this API is supported in atomic services. |
| name11+ | string | No | No | Name of the task specified when the task is created. You are advised not to change the value. Atomic service API: This API can be used in atomic services since API version 11. |
| taskId18+ | number | No | No | ID of the task. The system provides a globally unique value by default. It is not recommended to modify this value. Atomic service API: Since API version 18, this API is supported in atomic services. |
| totalDuration11+ | number | No | No | Total time consumed by task execution. Unit: ms. It is not recommended to modify this value. Atomic service API: Since API version 11, this API is supported in atomic services. |
| ioDuration11+ | number | No | No | Time consumed by asynchronous I/O during task execution. Unit: ms. It is not recommended to modify this value. Atomic service API: Since API version 11, this API is supported in atomic services. |
| cpuDuration11+ | number | No | No | CPU time consumed by task execution. Unit: ms. It is not recommended to modify this value. Atomic service API: Since API version 11, this API is supported in atomic services. |
constructor(func: Function, ...args: Object[])
A constructor used to create a Task instance.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| func | Function | Yes | Function to execute. It must be decorated by @Concurrent. For the supported return value types, see Sequenceable Data Types. |
| args | Object[] | No | Input parameters of the task function. For the supported parameter types, see Sequenceable Data Types. The default value is undefined. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200014 | The function is not marked as concurrent. |
Example
@Concurrent
function printArgs(args: string): string {
console.info("printArgs: " + args);
return args;
}
let task: taskpool.Task = new taskpool.Task(printArgs, "this is my first Task"); constructor(name: string, func: Function, ...args: Object[])
A constructor used to create a Task instance, with the task name specified.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| name | string | Yes | Task name. |
| func | Function | Yes | Function to execute. It must be decorated by @Concurrent. For details about the supported return value types of the function, see Sequenceable Data Types. |
| args | Object[] | No | Arguments of the task execution function. For details about the supported types, see Sequenceable Data Types. The default value is undefined. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200014 | The function is not marked as concurrent. |
Example
@Concurrent
function printArgs(args: string): string {
console.info("printArgs: " + args);
return args;
}
let taskName: string = "taskName";
let task: taskpool.Task = new taskpool.Task(taskName, printArgs, "this is my first Task");
let name: string = task.name; static isCanceled(): boolean
Checks whether the running task is canceled. Before using this method, you need to create a Task object.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Return value
| Type | Description |
|---|---|
| boolean | If the task is canceled, true is returned. Otherwise, false is returned. |
Example
@Concurrent
function inspectStatus(arg: number): number {
// ...
if (taskpool.Task.isCanceled()) {
console.info("task has been canceled.");
// ...
return arg + 1;
}
// ...
return arg;
}
isCanceled must be used together with taskpool.cancel. If cancel is not called, isCanceled returns false by default.
Example
import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
function inspectStatus(arg: number): number {
// Check whether the task has been canceled and respond accordingly.
if (taskpool.Task.isCanceled()) {
console.info("task has been canceled before 2s sleep.");
return arg + 2;
}
// Wait for 2s.
let t: number = Date.now();
while (Date.now() - t < 2000) {
continue;
}
// Check again whether the task has been canceled and respond accordingly.
if (taskpool.Task.isCanceled()) {
console.info("task has been canceled after 2s sleep.");
return arg + 3;
}
return arg + 1;
}
let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res: Object) => {
console.info("Succeeded in executing task, result: " + res);
}).catch((e: BusinessError) => {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
});
// If cancel is not called, isCanceled() returns false by default, and the task execution result is 101. setTransferList(transfer?: ArrayBuffer[]): void
Sets the transfer list of the task. Before using this method, you need to construct a Task object. If this API is not called, the ArrayBuffer in the data passed to the task is transferred by default.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| transfer | ArrayBuffer[] | No | ArrayBuffer instance holding the objects to transfer. The default value is an empty array. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200029 | An ArrayBuffer cannot be set as both a transfer list and a clone list. Applicable version: 11+ |
Example
@Concurrent
function testTransfer(arg1: ArrayBuffer, arg2: ArrayBuffer): number {
console.info("testTransfer arg1 byteLength: " + arg1.byteLength);
console.info("testTransfer arg2 byteLength: " + arg2.byteLength);
return 100;
}
let buffer: ArrayBuffer = new ArrayBuffer(8);
let view: Uint8Array = new Uint8Array(buffer);
let buffer1: ArrayBuffer = new ArrayBuffer(16);
let view1: Uint8Array = new Uint8Array(buffer1);
console.info("testTransfer view byteLength: " + view.byteLength);
console.info("testTransfer view1 byteLength: " + view1.byteLength);
// The execution result is as follows:
// testTransfer view byteLength: 8
// testTransfer view1 byteLength: 16
let task: taskpool.Task = new taskpool.Task(testTransfer, view, view1);
task.setTransferList([view.buffer, view1.buffer]);
taskpool.execute(task).then((res: Object) => {
console.info("test result: " + res);
}).catch((e: string) => {
console.error("test catch: " + e);
})
console.info("testTransfer view2 byteLength: " + view.byteLength);
console.info("testTransfer view3 byteLength: " + view1.byteLength);
// The value is 0 after transfer. The execution result is as follows:
// testTransfer view2 byteLength: 0
// testTransfer view3 byteLength: 0 setCloneList(cloneList: Object[] | ArrayBuffer[]): void
Sets the task clone list. Before using this method, you need to construct a Task object.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| cloneList | Object[] | ArrayBuffer[] | Yes | - The type of the passed-in array must be sendable data types or ArrayBuffer. - All 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. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200029 | An ArrayBuffer cannot be set as both a transfer list and a clone list. |
Example
// sendable.ets
// Define two Sendable classes: BaseClass and its child class DeriveClass.
@Sendable
export class BaseClass {
private str: string = "sendable: BaseClass";
static num :number = 10;
str1: string = "sendable: this is BaseClass's string";
num1: number = 5;
isDone1: boolean = false;
private fibonacciRecursive(n: number): number {
if (n <= 1) {
return n;
} else {
return this.fibonacciRecursive(n - 1) + this.fibonacciRecursive(n - 2);
}
}
private privateFunc(num: number): number{
let res: number = this.fibonacciRecursive(num);
console.info("sendable: BaseClass privateFunc res is: " + res);
return res;
}
publicFunc(num: number): number {
return this.privateFunc(num);
}
get GetNum(): number {
return this.num1;
}
set SetNum(num: number) {
this.num1 = num;
}
constructor() {
console.info(this.str);
this.isDone1 = true;
}
}
@Sendable
export class DeriveClass extends BaseClass {
name: string = "sendable: this is DeriveClass";
printName() {
console.info(this.name);
}
constructor() {
super();
}
} // index.ets
// The host thread (UI main thread) calls the methods of BaseClass and DeriveClass in the task pool thread and accesses their properties.
import { taskpool } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
import { BaseClass, DeriveClass } from './sendable';
@Concurrent
function testFunc(arr: Array<BaseClass>, num: number): number {
let baseInstance1 = arr[0];
console.info("sendable: str1 is: " + baseInstance1.str1);
baseInstance1.SetNum = 100;
console.info("sendable: num1 is: " + baseInstance1.GetNum);
console.info("sendable: isDone1 is: " + baseInstance1.isDone1);
// Obtain the result of the item specified by num from Fibonacci sequence.
let res: number = baseInstance1.publicFunc(num);
return res;
}
@Concurrent
function printLog(arr: Array<DeriveClass>): void {
let deriveInstance = arr[0];
deriveInstance.printName();
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text("TaskPool Test");
}.onClick(() => {
// task1 calls BaseClass.str1/BaseClass.SetNum/BaseClass.GetNum/BaseClass.isDone1/BaseClass.publicFunc.
let baseInstance1: BaseClass = new BaseClass();
let array1 = new Array<BaseClass>();
array1.push(baseInstance1);
let task1 = new taskpool.Task(testFunc, array1, 10);
task1.setCloneList(array1);
taskpool.execute(task1).then((res: Object) => {
console.info("sendable: task1 res is: " + res);
}).catch((e:BusinessError) => {
console.error(`sendable: task1 execute Code is ${e.code}, message is ${e.message}`);
})
// task2 calls DeriveClass.printName.
let deriveInstance: DeriveClass = new DeriveClass();
let array2 = new Array<DeriveClass>();
array2.push(deriveInstance);
let task2 = new taskpool.Task(printLog, array2);
task2.setCloneList(array2);
taskpool.execute(task2).then(() => {
console.info("sendable: task2 execute success");
}).catch((e:BusinessError) => {
console.error(`sendable: task2 execute Code is ${e.code}, message is ${e.message}`);
})
})
.height('15%')
.width('30%')
}
.width('100%')
}
.height('100%')
}
} static sendData(...args: Object[]): void
Sends data to the host thread and triggers the registered callback. Before calling this method, you need to construct a Task object.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| args | Object[] | No | Data to be used as the argument of the registered callback. For details about the supported parameter types, see Sequenceable Data Types. The default value is undefined. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. |
| 10200022 | The function is not called in the TaskPool thread. |
| 10200023 | The function is not called in the concurrent function. |
| 10200024 | The callback is not registered on the host side. |
Example
@Concurrent
function sendDataTest(num: number): number {
let res: number = num * 10;
taskpool.Task.sendData(res);
return num;
}
function printLog(data: number): void {
console.info("taskpool: data is: " + data);
}
async function taskpoolTest(): Promise<void> {
try {
let task: taskpool.Task = new taskpool.Task(sendDataTest, 1);
task.onReceiveData(printLog);
await taskpool.execute(task);
} catch (e) {
console.error(`taskpool: error code: ${e.code}, message: ${e.message}`);
}
}
taskpoolTest(); // Call this method in an asynchronous function.
@Concurrent
async function sendDataTest(num: number) {
let asyncSleepAndSendData = async () => {
let asyncSleep = async (time: number): Promise<Object> => {
return new Promise(resolve => setTimeout(resolve, time));
}
await asyncSleep(10000);
let res: number = num * 10;
taskpool.Task.sendData(res);
}
await asyncSleepAndSendData(); // Use await to ensure that the asynchronous function completes synchronously within the task.
}
function taskpoolTest() {
try {
let task: taskpool.Task = new taskpool.Task(sendDataTest, 10);
task.onReceiveData((data: number) => {
console.info("taskpool: data is: " + data);
});
taskpool.execute(task);
} catch (e) {
console.error(`taskpool: error code: ${e.code}, info: ${e.message}`);
}
}
taskpoolTest(); onReceiveData(callback?: Function): void
Registers a callback for a task to receive and process data from the worker thread. Before calling this method, you need to construct a Task object.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| 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. |
Example
@Concurrent
function concurrentFunc(num: number): number {
let res: number = num * 10;
taskpool.Task.sendData(res);
return num;
}
function printLog(data: number): void {
console.info("taskpool: data is: " + data);
}
async function testFunc(): Promise<void> {
try {
let task: taskpool.Task = new taskpool.Task(concurrentFunc, 1);
task.onReceiveData(printLog);
await taskpool.execute(task);
} catch (e) {
console.error(`taskpool: error code: ${e.code}, message: ${e.message}`);
}
}
testFunc(); addDependency(...tasks: Task[]): void
Adds 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.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| tasks | Task[] | No | Array of tasks on which the current task depends. The default value is undefined. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200026 | There is a circular dependency. |
| 10200052 | The periodic task cannot have a dependency. Applicable version: 12+ |
| 10200056 | The task has been executed by the AsyncRunner. Applicable version: 18+ |
Example
@Concurrent
function delay(args: number): number {
let t: number = Date.now();
while ((Date.now() - t) < 1000) {
continue;
}
return args;
}
let task1:taskpool.Task = new taskpool.Task(delay, 100);
let task2:taskpool.Task = new taskpool.Task(delay, 200);
let task3:taskpool.Task = new taskpool.Task(delay, 200);
console.info("dependency: add dependency start");
task1.addDependency(task2);
task2.addDependency(task3);
console.info("dependency: add dependency end");
console.info("dependency: start execute second");
taskpool.execute(task1).then(() => {
console.info("dependency: second task1 success");
})
taskpool.execute(task2).then(() => {
console.info("dependency: second task2 success");
})
taskpool.execute(task3).then(() => {
console.info("dependency: second task3 success");
}) removeDependency(...tasks: Task[]): void
Removes dependent tasks for this task. Before using this method, you need to construct a Task object.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| tasks | Task[] | No | Array of tasks on which the current task depends. The default value is undefined. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200027 | The dependency does not exist. |
| 10200052 | The periodic task cannot have a dependency. Applicable version: 12+ |
| 10200056 | The task has been executed by the AsyncRunner. Applicable version: 18+ |
Example
@Concurrent
function delay(args: number): number {
let t: number = Date.now();
while ((Date.now() - t) < 1000) {
continue;
}
return args;
}
let task1:taskpool.Task = new taskpool.Task(delay, 100);
let task2:taskpool.Task = new taskpool.Task(delay, 200);
let task3:taskpool.Task = new taskpool.Task(delay, 200);
console.info("dependency: add dependency start");
task1.addDependency(task2);
task2.addDependency(task3);
console.info("dependency: add dependency end");
console.info("dependency: remove dependency start");
task1.removeDependency(task2);
task2.removeDependency(task3);
console.info("dependency: remove dependency end");
console.info("dependency: start execute");
taskpool.execute(task1).then(() => {
console.info("dependency: task1 success");
})
taskpool.execute(task2).then(() => {
console.info("dependency: task2 success");
})
taskpool.execute(task3).then(() => {
console.info("dependency: task3 success");
}) onEnqueued(callback: CallbackFunction): void
Registers a callback function that is invoked when the task is enqueued. It must be registered before execute is called; otherwise, an exception is thrown.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | CallbackFunction | Yes | Callback function to register. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200034 | The executed task does not support the registration of listeners. |
Example
import { taskpool } from '@kit.ArkTS';
@Concurrent
function delay(args: number): number {
let t: number = Date.now();
while ((Date.now() - t) < 1000) {
continue;
}
return args;
}
let task: taskpool.Task = new taskpool.Task(delay, 1);
task.onEnqueued(() => {
console.info("taskpool: onEnqueued");
});
taskpool.execute(task).then(() => {
console.info("taskpool: execute task success");
}); onStartExecution(callback: CallbackFunction): void
Registers a callback function that is invoked before the task starts execution. It must be registered before execute is called; otherwise, an exception is thrown.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | CallbackFunction | Yes | Callback function to register. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200034 | The executed task does not support the registration of listeners. |
Example
import { taskpool } from '@kit.ArkTS';
@Concurrent
function delay(args: number): number {
let t: number = Date.now();
while ((Date.now() - t) < 1000) {
continue;
}
return args;
}
let task: taskpool.Task = new taskpool.Task(delay, 1);
task.onStartExecution(() => {
console.info("taskpool: onStartExecution");
});
taskpool.execute(task).then(() => {
console.info("taskpool: execute task success");
}); onExecutionFailed(callback: CallbackFunctionWithError): void
Registers a callback function that is invoked when the task fails to execute (not supported for periodic tasks). It must be registered before execute is called; otherwise, an exception is thrown.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | CallbackFunctionWithError | Yes | Callback function to register. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200034 | The executed task does not support the registration of listeners. |
Example
import { taskpool } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
import { HashMap } from '@kit.ArkTS';
@Concurrent
function hashMapFunc(args: number) {
let t = Date.now();
while ((Date.now() - t) < 100) {
continue;
}
return () => {};
}
let task2 = new taskpool.Task(hashMapFunc, 1);
task2.onExecutionFailed((e: Error) => {
console.error("taskpool: onExecutionFailed error is " + e.message);
})
taskpool.execute(task2).then(() => {
console.info("taskpool: execute task success");
}).catch((e:BusinessError) => {
console.error(`taskpool: error code: ${e.code}, error message: ${e.message}`);
}) onExecutionSucceeded(callback: CallbackFunction): void
Registers a callback function that is invoked when the task is executed successfully (not supported for periodic tasks). It must be registered before execute is called; otherwise, an exception is thrown.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | CallbackFunction | Yes | Callback function to register. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200034 | The executed task does not support the registration of listeners. |
Example
import { taskpool } from '@kit.ArkTS';
@Concurrent
function delay(args: number): number {
let t: number = Date.now();
while ((Date.now() - t) < 1000) {
continue;
}
return args;
}
let task: taskpool.Task = new taskpool.Task(delay, 1);
task.onExecutionSucceeded(() => {
console.info("taskpool: onExecutionSucceeded");
});
taskpool.execute(task).then(() => {
console.info("taskpool: execute task success");
}); isDone(): boolean
Checks whether the task is complete.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Return value
| Type | Description |
|---|---|
| boolean | Check result. The value true is returned if the task is complete; otherwise, false is returned. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
function inspectStatus(arg: number): number {
// 1s sleep
let t: number = Date.now();
while (Date.now() - t < 1000) {
continue;
}
return arg + 1;
}
async function taskpoolCancel(): Promise<void> {
let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res: Object) => {
console.info("Succeeded in executing task, result: " + res);
}).catch((e: BusinessError) => {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
});
setTimeout(() => {
if (!task.isDone()) {
taskpool.cancel(task);
}
}, 3000); // Wait for 3s to ensure that the task has been executed.
}
taskpoolCancel(); type CallbackFunction = () => void
Describes a callback function.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
type CallbackFunctionWithError = (e: Error) => void
Registers the type of the callback function that receives the error object.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| e | Error | Yes | Error message object. |
Describes a continuous task. LongTask inherits from Task.
No 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.
The thread for executing a continuous task exists until terminateTask is called after the execution is complete. The thread is reclaimed when it is idle.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Example
@Concurrent
function printArgs(args: string): string {
console.info("printArgs: " + args);
return args;
}
let task: taskpool.LongTask = new taskpool.LongTask(printArgs, "this is my first LongTask"); Implements a generic task. GenericsTask inherits from Task.
During 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.
System capability: SystemCapability.Utils.Lang
constructor(func: (...args: A) => R | Promise<R>, ...args: A)
A constructor used to create a GenericsTask object.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 13.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| func | (...args: A) => R | Promise<R> | Yes | Function to be executed. It must be decorated by the @Concurrent decorator. For the supported return value types, see Sequenceable Data Types. |
| args | A | No | Input parameters of the task execution function. For the supported parameter types, see Sequenceable Data Types. The default value is undefined. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200014 | The function is not marked as concurrent. |
Example
@Concurrent
function printArgs(args: string): string {
console.info("printArgs: " + args);
return args;
}
@Concurrent
function testWithThreeParams(a: number, b: string, c: number): string {
return b;
}
@Concurrent
function testWithArray(args: [number, string]): string {
return "success";
}
let task1: taskpool.Task = new taskpool.GenericsTask<[string], string>(printArgs, "this is my first GenericsTask");
let task2: taskpool.Task = new taskpool.GenericsTask<[number, string, number], string>(testWithThreeParams, 100, "test", 100);
let task3: taskpool.Task = new taskpool.GenericsTask<[[number, string]], string>(testWithArray, [100, "test"]); constructor(name: string, func: (...args: A) => R | Promise<R>, ...args: A)
A constructor used to create a GenericsTask instance, with the task name specified.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 13.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| name | string | Yes | Name of the generic task. |
| func | (...args: A) => R | Promise<R> | Yes | Function to execute. It must be decorated by @Concurrent. For the supported return value types, see Sequenceable Data Types. |
| args | A | No | Arguments of the function. For details about the supported parameter types, see Sequenceable Data Types. The default value is undefined. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200014 | The function is not marked as concurrent. |
Example
@Concurrent
function printArgs(args: string): string {
console.info("printArgs: " + args);
return args;
}
let taskName: string = "taskName";
let task: taskpool.Task = new taskpool.GenericsTask<[string], string>(taskName, printArgs, "this is my first Task");
let name: string = task.name; Represents a task group, which executes a group of tasks at a time. It is applicable to executing a group of associated tasks.
constructor()
Constructor used to create a TaskGroup instance.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Example
let taskGroup = new taskpool.TaskGroup();
constructor(name: string)
A constructor used to create a TaskGroup instance, with the task group name specified.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| name | string | Yes | Task group name. |
Example
let taskGroupName: string = "groupName"; let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(taskGroupName); let name: string = taskGroup.name;
addTask(func: Function, ...args: Object[]): void
Adds the function to be executed to this task group. Before using this API, you must create a TaskGroup instance.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| func | Function | Yes | Function to execute. It must be decorated by @Concurrent. For the supported return value types of the function, see Sequenceable Data Types. |
| args | Object[] | No | Arguments of the function. For details about the supported parameter types, see Sequenceable Data Types. The default value is undefined. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200014 | The function is not marked as concurrent. |
Example
@Concurrent
function printArgs(args: number): number {
console.info("printArgs: " + args);
return args;
}
let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup.addTask(printArgs, 100); // 100: test number addTask(task: Task): void
Adds 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.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| task | Task | Yes | Task to be added to the task group. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200014 | The function is not marked as concurrent. |
| 10200051 | The periodic task cannot be executed again. Applicable version: 12+ |
| 10200057 | The task cannot be executed by two APIs. Applicable version: 18+ |
Example
@Concurrent
function printArgs(args: number): number {
console.info("printArgs: " + args);
return args;
}
let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
taskGroup.addTask(task); System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| name11+ | string | No | No | Name of the task group specified when the task group is created. |
constructor(priority?: Priority)
A constructor used to create a SequenceRunner instance.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| priority | Priority | No | Priority of the task. The default value is taskpool.Priority.MEDIUM. |
Example
let runner: taskpool.SequenceRunner = new taskpool.SequenceRunner();
constructor(name: string, priority?: Priority)
A 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.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| name | string | Yes | Name of a serial queue. |
| priority | Priority | No | Priority of the task. The default value is taskpool.Priority.MEDIUM. |
Example
let runner:taskpool.SequenceRunner = new taskpool.SequenceRunner("runner1", taskpool.Priority.LOW); execute(task: Task): Promise<Object>
Adds 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. This API uses a promise to return the result.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| task | Task | Yes | Task to be added to the serial queue. |
Return value
| Type | Description |
|---|---|
| Promise<Object> | Promise object, which returns the execution result of the task function. |
Error codes
For details about the following error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200003 | Worker initialization failed. Applicable version: 11-17 |
| 10200006 | An exception occurred during serialization. |
| 10200025 | dependent task not allowed. |
| 10200051 | The periodic task cannot be executed again. Applicable version: 12+ |
| 10200057 | The task cannot be executed by two APIs. Applicable version: 18+ |
Example
@Concurrent
function additionDelay(delay: number): void {
let start: number = new Date().getTime();
while (new Date().getTime() - start < delay) {
continue;
}
}
@Concurrent
function waitForRunner(finalString: string): string {
return finalString;
}
async function seqRunner() {
let finalString:string = "";
let task1:taskpool.Task = new taskpool.Task(additionDelay, 3000);
let task2:taskpool.Task = new taskpool.Task(additionDelay, 2000);
let task3:taskpool.Task = new taskpool.Task(additionDelay, 1000);
let task4:taskpool.Task = new taskpool.Task(waitForRunner, finalString);
let runner:taskpool.SequenceRunner = new taskpool.SequenceRunner();
runner.execute(task1).then(() => {
finalString += 'a';
console.info("seqrunner: task1 done.");
});
runner.execute(task2).then(() => {
finalString += 'b';
console.info("seqrunner: task2 done");
});
runner.execute(task3).then(() => {
finalString += 'c';
console.info("seqrunner: task3 done");
});
await runner.execute(task4);
console.info("seqrunner: task4 done, finalString is " + finalString);
} Implements an asynchronous queue, for which you can specify the task execution concurrency and queuing policy.
constructor(runningCapacity: number, waitingCapacity?: number)
Constructor of AsyncRunner. Constructs a non-global asynchronous queue. Even if the parameters are the same, each call returns a different asynchronous queue instance.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 18.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| 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. |
| 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. |
Example
let runner: taskpool.AsyncRunner = new taskpool.AsyncRunner(5);
constructor(name: string, runningCapacity: number, waitingCapacity?: number)
A constructor used to create an AsyncRunner instance. It constructs a global asynchronous queue. If the queue name is the same as an existing name, the same asynchronous queue is returned.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 18.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| name | string | Yes | Name of an asynchronous queue. |
| 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. |
| 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. |
Example
let runner:taskpool.AsyncRunner = new taskpool.AsyncRunner("runner1", 5, 5); execute(task: Task, priority?: Priority): Promise<Object>
Adds a task to the asynchronous queue for execution. Before using this API, you must create an AsyncRunner instance. This API uses a promise to return the result.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 18.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| task | Task | Yes | Task to be added to the asynchronous queue. |
| priority | Priority | No | Priority of the task. The default value is taskpool.Priority.MEDIUM. |
Return value
| Type | Description |
|---|---|
| Promise<Object> | Promise object, which returns the execution result of the task function. |
Error codes
For details about the error codes, see Utils Error Codes.
| ID | Error Message |
|---|---|
| 10200006 | An exception occurred during serialization. |
| 10200025 | dependent task not allowed. |
| 10200051 | The periodic task cannot be executed again. |
| 10200054 | The asyncRunner task is discarded. |
| 10200057 | The task cannot be executed by two APIs. |
Example
import { taskpool } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
function additionDelay(delay: number): void {
let start: number = new Date().getTime();
while (new Date().getTime() - start < delay) {
continue;
}
}
async function asyncRunner() {
let runner:taskpool.AsyncRunner = new taskpool.AsyncRunner("runner1", 5, 5);
for (let i = 0; i < 30; i++) {
let task:taskpool.Task = new taskpool.Task(additionDelay, 1000);
runner.execute(task).then(() => {
console.info("asyncRunner: task" + i + " done.");
}).catch((e: BusinessError) => {
console.error("asyncRunner: task" + i + " error." + e.code + "-" + e.message);
});
}
}
async function asyncRunner2() {
let runner:taskpool.AsyncRunner = new taskpool.AsyncRunner(5);
for (let i = 0; i < 20; i++) {
let task:taskpool.Task = new taskpool.Task(additionDelay, 1000);
runner.execute(task).then(() => {
console.info("asyncRunner: task" + i + " done.");
});
}
} Enumerates the states of a task (Task).
The state transition rules are as follows:
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
| Name | Value | Description |
|---|---|---|
| WAITING | 1 | The task is waiting. |
| RUNNING | 2 | The task is running. |
| CANCELED | 3 | The task is canceled. |
Describes the internal information about a task.
System capability: SystemCapability.Utils.Lang
System capability: SystemCapability.Utils.Lang
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| name12+ | string | No | No | Task name. You are advised not to change the value. Atomic service API: This API can be used in atomic services since API version 12. |
| taskId | number | No | No | ID of the task. The system provides a globally unique value by default, and modifying this value is not recommended. Atomic service API: This API can be used in atomic services since API version 11. |
| state | State | No | No | Task state. You are advised not to change the value. Atomic service API: This API can be used in atomic services since API version 11. |
| duration | number | No | Yes | Time elapsed since the task started execution. The default value is 0, in ms. A return value of 0 indicates that the task has not been executed; an empty return value indicates that no task is being executed. Modifying this value is not recommended. Atomic service API: This API can be used in atomic services since API version 11. |
Describes the internal information about a worker thread.
System capability: SystemCapability.Utils.Lang
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| tid | number | No | No | ID of the worker thread. If the return value is empty, no task is running. You are advised not to change the value. |
| taskIds | number[] | No | Yes | IDs of tasks running on the calling thread. If the return value is empty, no task is running. You are advised not to change the value. |
| priority | Priority | No | Yes | Priority of the calling thread. If the return value is empty, no task is running. You are advised not to change the value. |
Describes the internal information about a task pool.
System capability: SystemCapability.Utils.Lang
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 11.
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| threadInfos | ThreadInfo[] | No | No | Internal information of the worker thread. It is not recommended to modify this value. |
| taskInfos | TaskInfo[] | No | No | Internal information of the task. It is not recommended to modify this value. |
After a cancel operation is performed on a task that is in the waiting or executing state, the supplementary information is captured in the BusinessError in the catch branch. In other scenarios, this information is undefined.
System capability: SystemCapability.Utils.Lang
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 20.
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| result | Object | No | Yes | Task execution result. The default value is undefined. You are advised not to change the value. |
| error | Error | Object | No | Yes | Error message. By default, the value is the same as the message field of BusinessError. You are advised not to change the value. |
After a task is canceled, the following situations may occur:
Example
import { taskpool } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit'
@Concurrent
function loop(): Error | number {
let start: number = Date.now();
while (Date.now() - start < 1500) {
}
if (taskpool.Task.isCanceled()) {
return 0;
}
while (Date.now() - start < 3000) {
}
if (taskpool.Task.isCanceled()) {
throw new Error("this is loop error");
}
return 1;
}
// Cancel the task before it starts execution.
function waitingCancel() {
let task = new taskpool.Task(loop);
taskpool.executeDelayed(2000, task).catch((e:BusinessError<taskpool.TaskResult>) => {
console.error(`waitingCancel task catch code: ${e.code}, message: ${e.message}`);
// waitingCancel task catch code: 0, message: taskpool:: task has been canceled
if (e.data !== undefined) {
console.error(`waitingCancel task catch data: result: ${e.data.result}, error: ${e.data.error}`);
// waitingCancel task catch data: result: undefined, error: taskpool:: task has been canceled
}
})
setTimeout(() => {
taskpool.cancel(task);
}, 1000);
}
// Cancel the task when it is running.
function runningCancel() {
let task = new taskpool.Task(loop);
taskpool.execute(task).catch((e:BusinessError<taskpool.TaskResult>) => {
console.error(`runningCancel task catch code: ${e.code}, message: ${e.message}`);
// runningCancel task catch code: 0, message: taskpool:: task has been canceled
if (e.data !== undefined) {
console.error(`runningCancel task catch data: result: ${e.data.result}, error: ${e.data.error}`);
// runningCancel task catch data: result: 0, error: taskpool:: task has been canceled
}
})
setTimeout(() => {
taskpool.cancel(task);
}, 1000);
}
// Throw an exception when the task is running.
function runningCancelError() {
let task = new taskpool.Task(loop);
taskpool.execute(task).catch((e:BusinessError<taskpool.TaskResult>) => {
console.error(`runningCancelError task catch code: ${e.code}, message: ${e.message}`);
// runningCancelError task catch code: 0, message: taskpool:: task has been canceled
if (e.data !== undefined) {
console.error(`runningCancelError task catch data: result: ${e.data.result}, error: ${e.data.error}`);
// runningCancelError task catch data: result: undefined, error: Error: this is loop error
}
})
setTimeout(() => {
taskpool.cancel(task);
}, 2000);
} Configuration items for a task or task group.
System capability: SystemCapability.Utils.Lang
Atomic service API: This API can be used in atomic services since API version 24.
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| timeout | number | No | Yes | Timeout duration, in ms. It is recommended to pass an integer. If a decimal is passed, it is rounded down. If this parameter is omitted, timeout takes the default value 0, and no timeout logic is executed. Note: 1. This timeout duration is not precise. Affected by thread scheduling, the actual timeout trigger time may deviate from the set value. 2. If the value is less than 1, it is set to 0 by default. 3. The timeout value is subject to system limits. If it exceeds 2^31 - 1, it overflows and the timeout value becomes 0. |
| priority | Priority | No | Yes | Priority of the task. The default value is taskpool.Priority.MEDIUM. |
For details about the supported serialization types, see Overview of Inter-Thread Communication Objects.
Example 1
// Common functions are supported, and variables passed in by input parameters are also supported.
@Concurrent
function printArgs(args: string): string {
console.info("func: " + args);
return args;
}
async function taskpoolExecute(): Promise<void> {
// taskpool.execute(task)
let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
console.info("taskpool.execute(task) result: " + await taskpool.execute(task));
// taskpool.execute(function)
console.info("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
}
taskpoolExecute(); Example 2
// b.ets export let sharedString: string = "hello";
// Reference an imported variable.
// a.ets (in the same directory as b.ets)
import { sharedString } from "./b";
@Concurrent
function printArgs(str: string): string {
console.info(str);
console.info(sharedString);
return str;
}
async function taskpoolExecute(): Promise<void> {
// taskpool.execute(task)
let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
console.info("taskpool.execute(task) result: " + await taskpool.execute(task));
// taskpool.execute(function)
console.info("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
}
taskpoolExecute(); Example 3
import { BusinessError } from '@kit.BasicServicesKit';
// The async functions are supported.
@Concurrent
async function delayExecute(): Promise<Array<Object>> {
let resolvedResults = await Promise.all<Object>([
new Promise<Object>(resolve => setTimeout(resolve, 1000, "resolved"))
]);
return resolvedResults;
}
async function taskpoolExecute(): Promise<void> {
taskpool.execute(delayExecute).then((result: Object) => {
console.info("Succeeded in executing task, result: " + result);
}).catch((e: BusinessError) => {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
});
}
taskpoolExecute(); Example 4
// c.ets
import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
function strSort(inputArr: Array<string>): Array<string> {
let newArr = inputArr.sort();
return newArr;
}
export async function executeByTaskObject(): Promise<void> {
console.info("taskpoolTest start");
let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
let task: taskpool.Task = new taskpool.Task(strSort, strArray);
console.info("func1 result:" + await taskpool.execute(task));
}
export async function executeByFunction(): Promise<void> {
console.info("taskpoolTest2 start");
let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
taskpool.execute(strSort, strArray).then((result: Object) => {
console.info("Succeeded in executing task, result: " + result);
}).catch((e: BusinessError) => {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
});
} // index.ets
import { executeByTaskObject, executeByFunction } from "./c";
executeByTaskObject();
executeByFunction(); Example 5
import { BusinessError } from '@kit.BasicServicesKit';
// Success in canceling a task
@Concurrent
function inspectStatus(arg: number): number {
// Check whether the task has been canceled and respond accordingly.
if (taskpool.Task.isCanceled()) {
console.info("task has been canceled before 2s sleep.");
return arg + 2;
}
// 2s sleep
let t: number = Date.now();
while (Date.now() - t < 2000) {
continue;
}
// Check again whether the task has been canceled and respond accordingly.
if (taskpool.Task.isCanceled()) {
console.info("task has been canceled after 2s sleep.");
return arg + 3;
}
return arg + 1;
}
async function taskpoolCancel(): Promise<void> {
let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res: Object) => {
console.info("Succeeded in executing task, result: " + res);
}).catch((e: BusinessError) => {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
});
// Cancel the task 1s later.
setTimeout(() => {
try {
taskpool.cancel(task);
} catch (e) {
console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
}
}, 1000);
}
taskpoolCancel(); Example 6
import { BusinessError } from '@kit.BasicServicesKit';
// Failure to cancel a task that has been executed
@Concurrent
function inspectStatus(arg: number): number {
// Check whether the task has been canceled and respond accordingly.
if (taskpool.Task.isCanceled()) {
return arg + 2;
}
// 0.5s latency
let t: number = Date.now();
while (Date.now() - t < 500) {
continue;
}
// Check again whether the task has been canceled and respond accordingly.
if (taskpool.Task.isCanceled()) {
return arg + 3;
}
return arg + 1;
}
async function taskpoolCancel(): Promise<void> {
let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res: Object) => {
console.info("Succeeded in executing task, result: " + res);
}).catch((e: BusinessError) => {
console.error(`Failed to execute task. Code: ${e.code}, message: ${e.message}`);
});
setTimeout(() => {
try {
taskpool.cancel(task); // The task has been executed and fails to be canceled.
} catch (e) {
console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
}
}, 3000); // Wait for 3s to ensure that the task has been executed.
}
taskpoolCancel(); Example 7
// Success of canceling a task group to be executed
@Concurrent
function printArgs(args: number): number {
let t: number = Date.now();
while (Date.now() - t < 1000) {
continue;
}
console.info("printArgs: " + args);
return args;
}
async function taskpoolGroupCancelTest(): Promise<void> {
let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
taskGroup1.addTask(printArgs, 20); // 20: test number
taskGroup1.addTask(printArgs, 30); // 30: test number
let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
taskGroup2.addTask(task1);
taskGroup2.addTask(task2);
taskGroup2.addTask(task3);
taskpool.execute(taskGroup1).then((res: Array<Object>) => {
console.info("taskpool execute res is:" + res);
}).catch((e: string) => {
console.error("taskpool execute error is:" + e);
});
taskpool.execute(taskGroup2).then((res: Array<Object>) => {
console.info("taskpool execute res is:" + res);
}).catch((e: string) => {
console.error("taskpool execute error is:" + e);
});
try {
taskpool.cancel(taskGroup2);
} catch (e) {
console.error(`Failed to cancel task. Code: ${e.code}, message: ${e.message}`);
}
}
taskpoolGroupCancelTest() Example 8
// Create and execute 100 tasks with different priorities, and view their information.
@Concurrent
function delay(): void {
let start: number = new Date().getTime();
while (new Date().getTime() - start < 500) {
continue;
}
}
let highCount: number = 0;
let mediumCount: number = 0;
let lowCount: number = 0;
let allCount: number = 100;
for (let i = 0; i < allCount; i++) {
let task1: taskpool.Task = new taskpool.Task(delay);
let task2: taskpool.Task = new taskpool.Task(delay);
let task3: taskpool.Task = new taskpool.Task(delay);
taskpool.execute(task1, taskpool.Priority.LOW).then(() => {
lowCount++;
}).catch((e: string) => {
console.error("low task error: " + e);
})
taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => {
mediumCount++;
}).catch((e: string) => {
console.error("medium task error: " + e);
})
taskpool.execute(task3, taskpool.Priority.HIGH).then(() => {
highCount++;
}).catch((e: string) => {
console.error("high task error: " + e);
})
}
let start: number = new Date().getTime();
while (new Date().getTime() - start < 1000) {
continue;
}
let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
let tid: number = 0;
let taskIds: Array<number> = [];
let priority: number = 0;
let taskId: number = 0;
let state: number = 0;
let duration: number = 0;
let name: string = "";
let threadInfos = Array.from(taskpoolInfo.threadInfos);
for (let threadInfo of threadInfos) {
tid = threadInfo.tid;
if (threadInfo.taskIds != undefined && threadInfo.priority != undefined) {
taskIds.length = threadInfo.taskIds.length;
priority = threadInfo.priority;
}
console.info("taskpool---tid is:" + tid + ", taskIds is:" + taskIds + ", priority is:" + priority);
}
let taskInfos = Array.from(taskpoolInfo.taskInfos);
for (let taskInfo of taskInfos) {
taskId = taskInfo.taskId;
state = taskInfo.state;
if (taskInfo.duration != undefined) {
duration = taskInfo.duration;
name = taskInfo.name;
}
console.info("taskpool---taskId is:" + taskId + ", state is:" + state + ", duration is:" + duration + ", name is:" + name);
} Example 9
// Obtain the exception information actively thrown during execution.
@Concurrent
function taskpoolThrow() {
throw new Error('execute error');
}
taskpool.execute(taskpoolThrow).catch((e: ESObject) => {
if (e.error) {
let errorMessage = e.error as Error;
console.error(`Failed to execute task. Error name: ${errorMessage.name}, error message: ${errorMessage.message}`);
} else {
console.error(`Failed to execute task. Error name: ${e.name}, error message: ${e.message}`);
}
});