• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Working with Task Queues Using JSVM-API
2
3## Introduction
4
5JSVM-API provides APIs for processing and dispatching the tasks that are queued up for execution. You can use the APIs to start the running of a task queue in a JSVM and check whether there are micro tasks waiting in the queue. The task queue can be executed cyclically by external events.
6
7## Basic Concepts
8
9- Task queue: a mechanism used to manage the scheduling and execution of asynchronous tasks to ensure that tasks are processed in sequence.
10- Micro task: a small task that needs to be executed as soon as possible. Micro tasks usually have a higher priority.
11
12## Available APIs
13
14| API| Description|
15| -------- | -------- |
16|OH_JSVM_PumpMessageLoop| Starts running a task queue.|
17|OH_JSVM_PerformMicrotaskCheckpoint| Executes micro tasks in a task queue.|
18## Example
19
20If you are just starting out with JSVM-API, see [JSVM-API Development Process](use-jsvm-process.md). The following demonstrates only the C++ and ArkTS code involved in the APIs for task queues.
21
22### OH_JSVM_PumpMessageLoop and OH_JSVM_PerformMicrotaskCheckpoint
23
24Use **OH_JSVM_PumpMessageLoop** to start running a task queue.
25
26CPP code:
27
28```cpp
29#include "napi/native_api.h"
30#include "ark_runtime/jsvm.h"
31#include <cassert>
32#include <string.h>
33#include "hilog/log.h"
34#include "napi/native_api.h"
35#include <unistd.h>
36#undef  LOG_TAG
37#define LOG_TAG "log"
38#undef  LOG_DOMAIN
39#define LOG_DOMAIN 0x1
40
41// Global variable, which is used to ensure that the VM is initialized only once.
42static int aa = 0;
43
44// JS code to be executed.
45static const char *STR_TASK = R"JS(
46new Promise((resolve,reject) => {
47    resolve(1)
48})
49.then(function(obj) {
50    consoleinfo("Called with instance " + obj);
51}).catch(function(err) {
52    consoleinfo("Called with error ");
53});
54)JS";
55
56// Ensure normal printing of the JS code information.
57static JSVM_Value ConsoleInfo(JSVM_Env env, JSVM_CallbackInfo info) {
58    size_t argc = 1;
59    JSVM_Value args[1];
60    char log[256] = "";
61    size_t logLength;
62    OH_JSVM_GetCbInfo(env, info, &argc, args, NULL, NULL);
63
64    OH_JSVM_GetValueStringUtf8(env, args[0], log, 255, &logLength);
65    log[255] = 0;
66    OH_LOG_INFO(LOG_APP, "JSVM API TEST: %{public}s", log);
67    return nullptr;
68}
69
70// Start executing the tasks in the task queue.
71static napi_value testHandleMicrotasks(napi_env env1, napi_callback_info info)
72{
73    JSVM_InitOptions init_options;
74    memset(&init_options, 0, sizeof(init_options));
75    if (aa == 0) {
76        OH_JSVM_Init(&init_options);
77        aa++;
78    }
79    // Create a JSVM instance and open the VM scope.
80    JSVM_VM vm;
81    JSVM_CreateVMOptions options;
82    memset(&options, 0, sizeof(options));
83    OH_JSVM_CreateVM(&options, &vm);
84    JSVM_VMScope vm_scope;
85    OH_JSVM_OpenVMScope(vm, &vm_scope);
86    // Register the consoleinfo callback.
87    JSVM_CallbackStruct param[] = {
88        {.data = nullptr, .callback = ConsoleInfo},
89    };
90    JSVM_PropertyDescriptor descriptor[] = {
91        {"consoleinfo", NULL, &param[0], NULL, NULL, NULL, JSVM_DEFAULT},
92    };
93    JSVM_Env env;
94    OH_JSVM_CreateEnv(vm, sizeof(descriptor) / sizeof(descriptor[0]), descriptor, &env);
95    JSVM_EnvScope envScope;
96    OH_JSVM_OpenEnvScope(env, &envScope);
97    JSVM_HandleScope handlescope;
98    OH_JSVM_OpenHandleScope(env, &handlescope);
99    JSVM_Value sourcecodevalue;
100    OH_JSVM_CreateStringUtf8(env, STR_TASK, strlen(STR_TASK), &sourcecodevalue);
101    JSVM_Script script;
102    OH_JSVM_CompileScript(env, sourcecodevalue, nullptr, 0, true, nullptr, &script);
103    JSVM_Value result;
104    OH_JSVM_RunScript(env, script, &result);
105    bool rst = false;
106    for (int i = 0; i < 3; i++) { // 3: cycles
107        // If no task is started in the message queue, set rst to false.
108        JSVM_Status flag1 = OH_JSVM_PumpMessageLoop(vm, &rst);
109        JSVM_Status flag2 = OH_JSVM_PerformMicrotaskCheckpoint(vm);
110        if (rst && flag1 == JSVM_Status::JSVM_OK && flag2 == JSVM_Status::JSVM_OK) {
111               sleep(3);
112               break;
113        }
114    }
115    // Close and destroy the environment and the VM.
116    OH_JSVM_CloseHandleScope(env, handlescope);
117    OH_JSVM_CloseEnvScope(env, envScope);
118    OH_JSVM_DestroyEnv(env);
119    OH_JSVM_CloseVMScope(vm, vm_scope);
120    OH_JSVM_DestroyVM(vm);
121    // Convert the return value of OH_JSVM_PumpMessageLoop to the Boolean type and output it.
122    napi_value result11;
123    napi_status status = napi_get_boolean(env1, rst, &result11);
124    assert(status == napi_ok);
125    return result11;
126}
127
128EXTERN_C_START
129static napi_value Init(napi_env env, napi_value exports)
130{
131    napi_property_descriptor desc[] = {
132        { "HandleMicrotasks", nullptr, testHandleMicrotasks, nullptr, nullptr, nullptr, napi_default, nullptr }
133    };
134    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
135    return exports;
136}
137EXTERN_C_END
138
139static napi_module demoModule = {
140    .nm_version = 1,
141    .nm_flags = 0,
142    .nm_filename = nullptr,
143    .nm_register_func = Init,
144    .nm_modname = "entry",
145    .nm_priv = ((void*)0),
146    .reserved = { 0 },
147};
148
149extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
150{
151    napi_module_register(&demoModule);
152}
153```
154
155ArkTS code:
156
157```ts
158import { hilog } from '@kit.PerformanceAnalysisKit';
159import testNapi from 'libentry.so';
160
161@Entry
162@Component
163struct Index {
164  @State message: string = 'Perform task';
165
166  build() {
167    Row() {
168      Column() {
169        Text(this.message)
170          .fontSize(50)
171          .fontWeight(FontWeight.Bold)
172          .onClick(() => {
173            let result = testNapi.HandleMicrotasks();
174            console.info ("Whether the tasks in the queue are started: "+result);
175
176          })
177      }
178      .width('100%')
179    }
180    .height('100%')
181  }
182}
183```
184