1 /*
2  * Copyright (c) 2023-2024 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 #include "hilog_tag_wrapper.h"
16 #include "ohos_loop_handler.h"
17 
18 namespace OHOS {
19 namespace AbilityRuntime {
20 
OnReadable(int32_t)21 void OHOSLoopHandler::OnReadable(int32_t)
22 {
23     TAG_LOGD(AAFwkTag::JSRUNTIME, "triggered");
24     OnTriggered();
25 }
26 
OnWritable(int32_t)27 void OHOSLoopHandler::OnWritable(int32_t)
28 {
29     TAG_LOGD(AAFwkTag::JSRUNTIME, "triggered");
30     OnTriggered();
31 }
32 
OnTriggered()33 void OHOSLoopHandler::OnTriggered()
34 {
35     TAG_LOGD(AAFwkTag::JSRUNTIME, "triggered");
36 
37     uv_run(uvLoop_, UV_RUN_NOWAIT);
38 
39     auto eventHandler = GetOwner();
40     if (!eventHandler) {
41         return;
42     }
43 
44     int32_t timeout = uv_backend_timeout(uvLoop_);
45     if (timeout < 0) {
46         if (haveTimerTask_) {
47             eventHandler->RemoveTask(TIMER_TASK);
48         }
49         return;
50     }
51 
52     int64_t timeStamp = static_cast<int64_t>(uv_now(uvLoop_)) + timeout;
53     // we don't check timestamp in emulator for computer clock is inaccurate
54 #ifndef RUNTIME_EMULATOR
55     if (timeStamp == lastTimeStamp_) {
56         return;
57     }
58 #endif
59 
60     if (haveTimerTask_) {
61         eventHandler->RemoveTask(TIMER_TASK);
62     }
63 
64     auto callback = [wp = weak_from_this()] {
65         auto sp = wp.lock();
66         if (sp) {
67             // Timer task is triggered, so there is no timer task now.
68             sp->haveTimerTask_ = false;
69             sp->OnTriggered();
70         }
71     };
72     eventHandler->PostTask(callback, TIMER_TASK, timeout);
73     lastTimeStamp_ = timeStamp;
74     haveTimerTask_ = true;
75 }
76 } // namespace AbilityRuntime
77 } // namespace OHOS
78