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 TIMER_TIMER_H 17 #define TIMER_TIMER_H 18 19 #include <map> 20 #include <mutex> 21 #include <uv.h> 22 23 #include "commonlibrary/ets_utils/js_concurrent_module/common/helper/napi_helper.h" 24 #include "commonlibrary/ets_utils/js_concurrent_module/common/helper/object_helper.h" 25 #include "napi/native_api.h" 26 #include "napi/native_node_api.h" 27 28 namespace OHOS::JsSysModule { 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 = Commonlibrary::Concurrent::Common::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 static bool HasTimer(napi_env env); 60 friend class TimerTest; 61 62 private: 63 static napi_value SetTimeout(napi_env env, napi_callback_info cbinfo); 64 static napi_value SetInterval(napi_env env, napi_callback_info cbinfo); 65 static napi_value ClearTimer(napi_env env, napi_callback_info cbinfo); 66 static napi_value SetTimeoutInner(napi_env env, napi_callback_info cbinfo, bool repeat); 67 static void TimerCallback(uv_timer_t* handle); 68 69 static uint32_t timeCallbackId; 70 static std::map<uint32_t, TimerCallbackInfo*> timerTable; 71 static std::mutex timeLock; 72 }; 73 } // namespace Commonlibrary::JsSysModule 74 #endif // TIMER_TIMER_H 75