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