js-apis-taskpool.md 14.3 KB
Newer Older
1
# @ohos.taskpool (Starting the Task Pool)
G
Gloria 已提交
2 3 4

The task pool provides a multi-thread running environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. You can use the **TaskPool** APIs to create background tasks and perform operations on them, for example, executing or canceling a task. Theoretically, you can create an unlimited number of tasks, but this is not recommended for memory considerations. In addition, you are not advised performing blocking operations in a task, especially indefinite blocking. Long-time blocking operations occupy worker threads and may block other task scheduling, adversely affecting your application performance.

5
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**.
G
Gloria 已提交
6

7
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.
G
Gloria 已提交
8 9 10 11 12 13 14 15

The **TaskPool** APIs return error codes in numeric format. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

> **NOTE**<br>
> 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.

## Modules to Import

G
Gloria 已提交
16
```ts
G
Gloria 已提交
17 18 19 20 21
import taskpool from '@ohos.taskpool';
```

## Priority

G
Gloria 已提交
22
Enumerates the priorities available for created tasks.
G
Gloria 已提交
23 24 25 26 27 28 29 30 31

**System capability**: SystemCapability.Utils.Lang

| Name| Value| Description|
| -------- | -------- | -------- |
| HIGH   | 0    | The task has a high priority.|
| MEDIUM | 1 | The task has a medium priority.|
| LOW | 2 | The task has a low priority.|

G
Gloria 已提交
32 33 34
**Example**

```ts
35 36 37
@Concurrent
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
38 39
    return args;
}
40 41
async function taskpoolPriority() {
  let task = new taskpool.Task(printArgs, 100);
G
Gloria 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

  let highCount = 0;
  let mediumCount = 0;
  let lowCount = 0;
  let allCount = 100;
  for (let i = 0; i < allCount; i++) {
    taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => {
      lowCount++;
      console.log("taskpool lowCount is :" + lowCount);
    }).catch((e) => {
      console.error("low task error: " + e);
    })
    taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => {
      mediumCount++;
      console.log("taskpool mediumCount is :" + mediumCount);
    }).catch((e) => {
      console.error("medium task error: " + e);
    })
    taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => {
      highCount++;
      console.log("taskpool highCount is :" + highCount);
    }).catch((e) => {
      console.error("high task error: " + e);
    })
  }
}
68
taskpoolPriority();
G
Gloria 已提交
69 70
```

G
Gloria 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
## Task

Implements a task. Before using any of the following APIs, you must create a **Task** instance.

### constructor

constructor(func: Function, ...args: unknown[])

A constructor used to create a **Task** instance.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type     | Mandatory| Description                                                                 |
| ------ | --------- | ---- | -------------------------------------------------------------------- |
| func   | Function  | Yes  | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).  |
G
Gloria 已提交
88
| args   | unknown[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
G
Gloria 已提交
89 90 91 92 93 94 95 96 97 98 99

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                               |
| -------- | --------------------------------------- |
| 10200014 | The function is not mark as concurrent. |

**Example**

G
Gloria 已提交
100 101
```ts
@Concurrent
102 103
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
104 105
    return args;
}
G
Gloria 已提交
106

107
let task = new taskpool.Task(printArgs, "this is my first Task");
G
Gloria 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
```

### Attributes

**System capability**: SystemCapability.Utils.Lang

| Name     | Type     | Readable| Writable| Description                                                                      |
| --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- |
| function  | Function  | Yes  | Yes  | Function to be passed in during task creation. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).  |
| arguments | unknown[] | Yes  | Yes  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|

## taskpool.execute

execute(func: Function, ...args: unknown[]): Promise\<unknown>

G
Gloria 已提交
123
Places the function to be executed in the internal task queue of the task pool. The function will be distributed to the worker thread for execution. The function to be executed in this mode cannot be canceled.
G
Gloria 已提交
124 125 126 127 128 129 130

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type     | Mandatory| Description                                                                  |
| ------ | --------- | ---- | ---------------------------------------------------------------------- |
G
Gloria 已提交
131 132
| func   | Function  | Yes  | Function to be executed. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
| args   | unknown[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
G
Gloria 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

**Return value**

| Type             | Description                                |
| ----------------- | ------------------------------------ |
| Promise\<unknown> | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                 |
| -------- | ----------------------------------------- |
| 10200003 | Worker initialization failure.            |
| 10200006 | Serializing an uncaught exception failed. |
| 10200014 | The function is not mark as concurrent.   |

**Example**

G
Gloria 已提交
152 153
```ts
@Concurrent
154 155
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
156 157 158
    return args;
}

159 160
async function taskpoolExecute() {
  let value = await taskpool.execute(printArgs, 100);
G
Gloria 已提交
161 162 163
  console.log("taskpool result: " + value);
}

164
taskpoolExecute();
G
Gloria 已提交
165 166 167 168 169 170
```

## taskpool.execute

execute(task: Task, priority?: Priority): Promise\<unknown>

G
Gloria 已提交
171
Places a task in the internal task queue of the task pool. The task will be distributed to the worker thread for execution. The task to be executed in this mode can be canceled.
G
Gloria 已提交
172 173 174 175 176

**System capability**: SystemCapability.Utils.Lang

**Parameters**

G
Gloria 已提交
177 178 179 180
| Name  | Type                 | Mandatory| Description                                      |
| -------- | --------------------- | ---- | ---------------------------------------- |
| task     | [Task](#task)         | Yes  | Task to be executed.                 |
| priority | [Priority](#priority) | No  | Priority of the task. The default value is **MEDIUM**.|
G
Gloria 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

**Return value**

| Type            | Description                          |
| ---------------- | ------------------------------ |
| Promise\<unknown> | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                 |
| -------- | ----------------------------------------- |
| 10200003 | Worker initialization failure.            |
| 10200006 | Serializing an uncaught exception failed. |
| 10200014 | The function is not mark as concurrent.   |

**Example**

G
Gloria 已提交
200 201
```ts
@Concurrent
202 203
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
204 205
    return args;
}
G
Gloria 已提交
206

207 208
async function taskpoolExecute() {
  let task = new taskpool.Task(printArgs, 100);
G
Gloria 已提交
209 210 211 212
  let value = await taskpool.execute(task);
  console.log("taskpool result: " + value);
}

213
taskpoolExecute();
G
Gloria 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
```

## taskpool.cancel

cancel(task: Task): void

Cancels a task in the task pool.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type         | Mandatory| Description                |
| ------ | ------------- | ---- | -------------------- |
| task   | [Task](#task) | Yes  | Task to cancel.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                 |
| -------- | ------------------------- |
| 10200015 | If the task is not exist. |
| 10200016 | If the task is running.   |

G
Gloria 已提交
239
**Example of successful task cancellation**
G
Gloria 已提交
240

G
Gloria 已提交
241
```ts
242 243 244
@Concurrent
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
245 246
    return args;
}
G
Gloria 已提交
247

248 249
async function taskpoolCancel() {
  let task = new taskpool.Task(printArgs, 100);
G
Gloria 已提交
250
  taskpool.execute(task);
G
Gloria 已提交
251 252 253 254 255
  try {
    taskpool.cancel(task);
  } catch (e) {
    console.log("taskpool.cancel occur error:" + e);
  }
G
Gloria 已提交
256 257
}

258
taskpoolCancel();
G
Gloria 已提交
259 260
```

G
Gloria 已提交
261 262 263
**Example of a failure to cancel a task that has been executed**

```ts
264 265 266
@Concurrent
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
267 268 269
    return args;
}

270 271
async function taskpoolCancel() {
  let task = new taskpool.Task(printArgs, 100);
G
Gloria 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284
  let value = taskpool.execute(task);
  let start = new Date().getTime();
  while (new Date().getTime() - start < 1000) {// Wait for 1s to ensure that the task has been executed.
    continue;
  }

  try {
    taskpool.cancel(task); // The task has been executed and fails to be canceled.
  } catch (e) {
    console.log("taskpool.cancel occur error:" + e);
  }
}

285
taskpoolCancel();
G
Gloria 已提交
286 287 288 289 290
```

**Example of a failure to cancel an ongoing task**

```ts
291 292 293
@Concurrent
function printArgs(args) {
    console.log("printArgs: " + args);
G
Gloria 已提交
294 295 296
    return args;
}

297 298 299 300 301 302 303
async function taskpoolCancel() {
  let task1 = new taskpool.Task(printArgs, 100);
  let task2 = new taskpool.Task(printArgs, 200);
  let task3 = new taskpool.Task(printArgs, 300);
  let task4 = new taskpool.Task(printArgs, 400);
  let task5 = new taskpool.Task(printArgs, 500);
  let task6 = new taskpool.Task(printArgs, 600);
G
Gloria 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317

  let res1 = taskpool.execute(task1);
  let res2 = taskpool.execute(task2);
  let res3 = taskpool.execute(task3);
  let res4 = taskpool.execute(task4);
  let res5 = taskpool.execute(task5);
  let res6 = taskpool.execute(task6);
  try {
    taskpool.cancel(task1); // task1 is being executed and fails to be canceled.
  } catch (e) {
    console.log("taskpool.cancel occur error:" + e);
  }
}

318
taskpoolCancel();
G
Gloria 已提交
319 320
```

G
Gloria 已提交
321 322 323 324 325 326
## Additional Information

### Sequenceable Data Types
The following sequenceable data types are supported: All Primitive Type (excluding symbol), Date, String, RegExp, Array, Map, Set, Object, ArrayBuffer, and TypedArray.

### Precautions
G
Gloria 已提交
327 328 329
- The task pool APIs can be used only in the module with **compileMode** set to **esmodule** in the stage model. To check the **compileMode** setting of a module, open the **build-profile.json5** file of the module and check for **"compileMode": "esmodule"** under **buildOption**.
- A task in the task pool can reference only variables passed in by input parameters or imported variables, rather than closure variables. The decorator **@Concurrent** is used to intercept unsupported variables.
- A task in the task pool supports only common functions or async functions, rather than class member functions or anonymous functions. The decorator **@Concurrent** is used to intercept unsupported functions.
330
- The decorator **@Concurrent** can be used only in .ets files.
G
Gloria 已提交
331

G
Gloria 已提交
332 333 334 335 336 337 338
### Using the Task Pool in Simple Mode

**Example 1**

```ts
// Common functions are supported, and variables passed in by input parameters are also supported.
@Concurrent
339
function printArgs(args) {
G
Gloria 已提交
340 341 342 343
    console.log("func: " + args);
    return args;
}

344
async function taskpoolExecute() {
G
Gloria 已提交
345
  // taskpool.execute(task)
346
  let task = new taskpool.Task(printArgs, "create task, then execute");
G
Gloria 已提交
347 348
  let val1 = await taskpool.execute(task);
  console.log("taskpool.execute(task) result: " + val1);
G
Gloria 已提交
349

G
Gloria 已提交
350
  // taskpool.execute(function)
351
  let val2 = await taskpool.execute(printArgs, "execute task by func");
G
Gloria 已提交
352 353 354
  console.log("taskpool.execute(function) result: " + val2);
}

355
taskpoolExecute();
G
Gloria 已提交
356 357
```

G
Gloria 已提交
358
**Example 2**
G
Gloria 已提交
359

G
Gloria 已提交
360 361
```ts
// b.ets
G
Gloria 已提交
362
export var c = 2000;
G
Gloria 已提交
363 364 365 366 367
```
```ts
// Reference an imported variable.
// a.ets (in the same directory as b.ets)
import { c } from "./b";
G
Gloria 已提交
368

G
Gloria 已提交
369
@Concurrent
370
function printArgs(a) {
G
Gloria 已提交
371 372 373 374 375
    console.log(a);
    console.log(c);
    return a;
}

376
async function taskpoolExecute() {
G
Gloria 已提交
377
  // taskpool.execute(task)
378
  let task = new taskpool.Task(printArgs, "create task, then execute");
G
Gloria 已提交
379 380 381 382
  let val1 = await taskpool.execute(task);
  console.log("taskpool.execute(task) result: " + val1);

  // taskpool.execute(function)
383
  let val2 = await taskpool.execute(printArgs, "execute task by func");
G
Gloria 已提交
384 385
  console.log("taskpool.execute(function) result: " + val2);
}
G
Gloria 已提交
386

387
taskpoolExecute();
G
Gloria 已提交
388
```
G
Gloria 已提交
389 390 391 392 393 394

**Example 3**

```ts
// The async functions are supported.
@Concurrent
395
async function delayExcute() {
G
Gloria 已提交
396 397 398 399 400 401
  let ret = await Promise.all([
    new Promise(resolve => setTimeout(resolve, 1000, "resolved"))
  ]);
  return ret;
}

402 403
async function taskpoolExecute() {
  taskpool.execute(delayExcute).then((result) => {
G
Gloria 已提交
404 405 406 407
    console.log("TaskPoolTest task result: " + result);
  });
}

408
taskpoolExecute();
G
Gloria 已提交
409 410 411 412 413
```

**Example 4**

```ts
414 415 416 417 418
// c.ets
@Concurrent
function strSort(inPutArr) {
  let newArr = inPutArr.sort();
  return newArr;
G
Gloria 已提交
419
}
420 421 422 423
export async function func1() {
    console.log("taskpoolTest start");
    let strArray = ['c test string', 'b test string', 'a test string'];
    var task = new taskpool.Task(strSort, strArray);
G
Gloria 已提交
424
    var result = await taskpool.execute(task);
425
    console.log("func1 result:" + result);
G
Gloria 已提交
426 427
}

428
export async function func2() {
G
Gloria 已提交
429
    console.log("taskpoolTest2 start");
430 431 432
    let strArray = ['c test string', 'b test string', 'a test string'];
    taskpool.execute(strSort, strArray).then((result) => {
        console.log("func2 result: " + result);
G
Gloria 已提交
433 434 435 436 437
    });
}
```

```ts
438
/ / a.ets (in the same directory as c.ets)
G
Gloria 已提交
439 440
import { taskpoolTest1, taskpoolTest2 } from "./c";

441 442
func1();
func2();
G
Gloria 已提交
443
```