• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 TELEPHONY_TIMER_H
17 #define TELEPHONY_TIMER_H
18 
19 #include <atomic>
20 #include <chrono>
21 #include <condition_variable>
22 #include <functional>
23 #include <memory>
24 #include <mutex>
25 #include <thread>
26 
27 #include "telephony_log_wrapper.h"
28 
29 namespace OHOS {
30 namespace Telephony {
31 class Timer {
32 public:
Timer()33     Timer() : stopStatus_(true), tryStopFlag_(false) {}
34 
Timer(const Timer & timer)35     Timer(const Timer &timer)
36     {
37         stopStatus_ = timer.stopStatus_.load();
38         tryStopFlag_ = timer.tryStopFlag_.load();
39     }
40 
~Timer()41     ~Timer()
42     {
43         stop();
44     }
45 
start(int interval,std::function<void ()> taskFun)46     void start(int interval, std::function<void()> taskFun)
47     {
48         if (stopStatus_ == false) {
49             return;
50         }
51         stopStatus_ = false;
52         std::thread([this, interval, taskFun]() {
53             while (!tryStopFlag_) {
54                 std::this_thread::sleep_for(std::chrono::milliseconds(interval));
55                 taskFun();
56             }
57             std::lock_guard<std::mutex> locker(mutex_);
58             stopStatus_ = true;
59             tryStopFlag_ = false;
60             timerCond_.notify_one();
61         }).detach();
62     }
63 
stop()64     void stop()
65     {
66         if (stopStatus_ || tryStopFlag_) {
67             return;
68         }
69         tryStopFlag_ = true;
70         {
71             std::unique_lock<std::mutex> locker(mutex_);
72             timerCond_.wait(locker, [this] { return stopStatus_ == true; });
73 
74             if (stopStatus_ == true)
75                 tryStopFlag_ = false;
76         }
77     }
78 
ThreadExit()79     void ThreadExit()
80     {
81         std::lock_guard<std::mutex> locker(mutex_);
82         stopStatus_ = true;
83         tryStopFlag_ = true;
84     }
85 
86 private:
87     std::atomic<bool> stopStatus_;
88     std::atomic<bool> tryStopFlag_;
89     std::mutex mutex_;
90     std::condition_variable timerCond_;
91 };
92 } // namespace Telephony
93 } // namespace OHOS
94 #endif // TELEPHONY_TIMER_H
95