• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef JS_CONCURRENT_MODULE_COMMON_PLUGIN_TIMER_H_
17 #define JS_CONCURRENT_MODULE_COMMON_PLUGIN_TIMER_H_
18 
19 #include <map>
20 #include <mutex>
21 #include <uv.h>
22 
23 #include "helper/napi_helper.h"
24 #include "helper/object_helper.h"
25 #include "napi/native_api.h"
26 #include "napi/native_node_api.h"
27 
28 namespace Commonlibrary::Concurrent::Common::Plugin {
29 struct TimerCallbackInfo {
30     napi_env env_;
31     uint32_t tId_;
32     int32_t timeout_;
33     napi_ref callback_;
34     bool repeat_;
35     uv_timer_t* timeReq_ = nullptr;
36     size_t argc_;
37     napi_ref* argv_;
38 
TimerCallbackInfoTimerCallbackInfo39     TimerCallbackInfo(napi_env env, uint32_t tId, int32_t timeout, napi_ref callback,
40                      bool repeat, size_t argc, napi_ref* argv)
41         : env_(env), tId_(tId), timeout_(timeout), callback_(callback),
42           repeat_(repeat), argc_(argc), argv_(argv)
43     {
44         uv_loop_t* loop = Helper::NapiHelper::GetLibUV(env_);
45         timeReq_ = new uv_timer_t;
46         uv_timer_init(loop, timeReq_);
47         timeReq_->data = this;
48     }
49 
50     ~TimerCallbackInfo();
51 };
52 
53 class Timer {
54 public:
55     Timer() = default;
56     ~Timer() = default;
57     static bool RegisterTime(napi_env env);
58     static void ClearEnvironmentTimer(napi_env env);
59 
60 private:
61     static napi_value SetTimeout(napi_env env, napi_callback_info cbinfo);
62     static napi_value SetInterval(napi_env env, napi_callback_info cbinfo);
63     static napi_value ClearTimer(napi_env env, napi_callback_info cbinfo);
64     static napi_value SetTimeoutInner(napi_env env, napi_callback_info cbinfo, bool repeat);
65     static void TimerCallback(uv_timer_t* handle);
66 
67     static uint32_t timeCallbackId;
68     static std::map<uint32_t, TimerCallbackInfo*> timerTable;
69     static std::mutex timeLock;
70 };
71 } // namespace Commonlibrary::Concurrent::Common::Plugin
72 #endif // JS_CONCURRENT_MODULE_COMMON_PLUGIN_TIMER_H_
73