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
16 #include "hgm_one_shot_timer.h"
17 #include "hgm_log.h"
18 #include "hgm_task_handle_thread.h"
19
20 namespace OHOS::Rosen {
21 namespace {
22 constexpr auto ZERO = std::chrono::steady_clock::duration::zero();
23 } // namespace
24
HgmSimpleTimer(std::string name,const Interval & interval,const StartCallback & startCallback,const ExpiredCallback & expiredCallback,std::unique_ptr<ChronoSteadyClock> clock)25 HgmSimpleTimer::HgmSimpleTimer(std::string name, const Interval& interval,
26 const StartCallback& startCallback, const ExpiredCallback& expiredCallback,
27 std::unique_ptr<ChronoSteadyClock> clock)
28 : name_(std::move(name)),
29 interval_(interval),
30 startCallback_(startCallback),
31 expiredCallback_(expiredCallback),
32 clock_(std::move(clock))
33 {
34 handler_ = HgmTaskHandleThread::Instance().CreateHandler();
35 }
36
Start()37 void HgmSimpleTimer::Start()
38 {
39 if (handler_ == nullptr) {
40 return;
41 }
42
43 bool isRunning = running_.exchange(true);
44 Reset(); // Reset() only take effect when running
45
46 // start
47 if (!isRunning) {
48 if (startCallback_) {
49 handler_->PostTask(startCallback_);
50 }
51 handler_->PostTask([this] () { Loop(); }, name_, interval_.count());
52 }
53 }
54
Stop()55 void HgmSimpleTimer::Stop()
56 {
57 if (running_.exchange(false) && handler_ != nullptr) {
58 handler_->RemoveTask(name_);
59 }
60 }
61
Reset()62 void HgmSimpleTimer::Reset()
63 {
64 if (running_.load() && clock_ != nullptr) {
65 resetTimePoint_.store(clock_->Now());
66 }
67 }
68
Loop()69 void HgmSimpleTimer::Loop()
70 {
71 auto delay = std::chrono::duration_cast<std::chrono::milliseconds>(
72 resetTimePoint_.load() + interval_ - clock_->Now());
73 if (delay > ZERO) {
74 // reset
75 if (running_.load() && handler_ != nullptr) {
76 handler_->PostTask([this] () { Loop(); }, name_, delay.count());
77 return;
78 }
79 } else {
80 // cb
81 if (expiredCallback_ != nullptr) {
82 handler_->PostTask(expiredCallback_);
83 }
84 }
85 running_.store(false);
86 }
87 } // namespace OHOS::Rosen