# @ohos.taskpool(启动任务池)
任务池(taskpool)作用是为应用程序提供一个多线程的运行环境,降低整体资源的消耗、提高系统的整体性能,且您无需关心线程实例的生命周期。您可以使用任务池API创建后台任务(Task),并对所创建的任务进行如任务执行、任务取消的操作。理论上您可以使用任务池API创建数量不受限制的任务,但是出于内存因素不建议您这样做。此外,不建议您在任务中执行阻塞操作,特别是无限期阻塞操作,长时间的阻塞操作占据工作线程,可能会阻塞其他任务调度,影响您的应用性能。
您所创建的同一优先级任务的执行顺序可以由您决定,任务真实执行的顺序与您调用任务池API提供的任务执行接口顺序一致。任务默认优先级是MEDIUM。
当同一时间待执行的任务数量大于任务池工作线程数量,任务池会根据负载均衡机制进行扩容,增加工作线程数量,减少整体等待时长。同样,当执行的任务数量减少,工作线程数量大于执行任务数量,部分工作线程处于空闲状态,任务池会根据负载均衡机制进行缩容,减少工作线程数量。
任务池API以数字形式返回错误码。有关各个错误码的更多信息,请参阅文档[语言基础类库错误码](../errorcodes/errorcode-utils.md)。
taskpool使用过程中的相关注意点请查[TaskPool注意事项](../../arkts-utils/taskpool-introduction.md#taskpool注意事项)。
> **说明:**
> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import taskpool from '@ohos.taskpool';
```
## taskpool.execute
execute(func: Function, ...args: unknown[]): Promise\
将待执行的函数放入taskpool内部任务队列等待,等待分发到工作线程执行。当前执行模式不可取消任务。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | --------- | ---- | ---------------------------------------------------------------------- |
| func | Function | 是 | 执行的逻辑需要传入函数,支持的函数返回值类型请查[序列化支持类型](#序列化支持类型)。 |
| args | unknown[] | 否 | 执行逻辑的函数所需要的参数,支持的参数类型请查[序列化支持类型](#序列化支持类型)。默认值为undefined。 |
**返回值:**
| 类型 | 说明 |
| ----------------- | ------------------------------------ |
| Promise\ | execute是异步方法,返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)。
| 错误码ID | 错误信息 |
| -------- | -------------------------------------------- |
| 10200003 | Worker initialization failure. |
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not mark as concurrent. |
**示例:**
```ts
@Concurrent
function printArgs(args: number): number {
console.log("printArgs: " + args);
return args;
}
taskpool.execute(printArgs, 100).then((value: number) => { // 100: test number
console.log("taskpool result: " + value);
});
```
## taskpool.execute
execute(task: Task, priority?: Priority): Promise\
将创建好的任务放入taskpool内部任务队列等待,等待分发到工作线程执行。当前执行模式可尝试调用cancel进行任务取消。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------------------------------------- |
| task | [Task](#task) | 是 | 需要在任务池中执行的任务。 |
| priority | [Priority](#priority) | 否 | 等待执行的任务的优先级,该参数默认值为taskpool.Priority.MEDIUM。 |
**返回值:**
| 类型 | 说明 |
| ---------------- | ---------------- |
| Promise\ | 返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)。
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------- |
| 10200003 | Worker initialization failure. |
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not mark as concurrent. |
**示例:**
```ts
@Concurrent
function printArgs(args: number): number {
console.log("printArgs: " + args);
return args;
}
let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
taskpool.execute(task).then((value: number) => {
console.log("taskpool result: " + value);
});
```
## taskpool.execute10+
execute(group: TaskGroup, priority?: Priority): Promise
将创建好的任务组放入taskpool内部任务队列等待,等待分发到工作线程执行。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | --------------------------- | ---- | -------------------------------------------------------------- |
| group | [TaskGroup](#taskgroup10) | 是 | 需要在任务池中执行的任务组。 |
| priority | [Priority](#priority) | 否 | 等待执行的任务组的优先级,该参数默认值为taskpool.Priority.MEDIUM。 |
**返回值:**
| 类型 | 说明 |
| ---------------- | ---------------------------------- |
| Promise\ | execute是异步方法,返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)。
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------- |
| 10200006 | An exception occurred during serialization. |
**示例:**
```ts
@Concurrent
function printArgs(args: number): number {
console.log("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) => {
console.info("taskpool execute res is:" + res);
});
taskpool.execute(taskGroup2).then((res: Array) => {
console.info("taskpool execute res is:" + res);
});
```
## taskpool.cancel
cancel(task: Task): void
取消任务池中的任务。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------- | ---- | -------------------- |
| task | [Task](#task) | 是 | 需要取消执行的任务。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)。
| 错误码ID | 错误信息 |
| -------- | -------------------------------------------- |
| 10200015 | The task does not exist when it is canceled. |
| 10200016 | The task is executing when it is canceled. |
从API version10开始,此接口调用时不再涉及上报错误码10200016。
**正在执行的任务取消示例:**
```ts
@Concurrent
function inspectStatus(arg: number): number {
// 第一次检查任务是否已经取消并作出响应
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;
}
// 第二次检查任务是否已经取消并作出响应
if (taskpool.Task.isCanceled()) {
console.info("task has been canceled after 2s sleep.");
return arg + 3;
}
return arg + 1;
}
function concurrntFunc() {
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("taskpool test result: " + res);
});
taskpool.execute(task2);
taskpool.execute(task3);
taskpool.execute(task4);
taskpool.execute(task5);
taskpool.execute(task6);
// 1s后取消task
setTimeout(()=>{
try {
taskpool.cancel(task1);
} catch (e) {
console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
}
}, 1000);
}
concurrntFunc();
```
## taskpool.cancel10+
cancel(group: TaskGroup): void
取消任务池中的任务组。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------- | ---- | -------------------- |
| group | [TaskGroup](#taskgroup10) | 是 | 需要取消执行的任务组。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)。
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------------------- |
| 10200018 | The task group does not exist when it is canceled. |
**示例:**
```ts
@Concurrent
function printArgs(args: number): number {
let t: number = Date.now();
while (Date.now() - t < 2000) {
continue;
}
console.info("printArgs: " + args);
return args;
}
function concurrntFunc() {
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