• 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 
16 #include "CppTimer.h"
17 
18 using namespace std;
19 using namespace std::chrono;
20 
~CppTimer()21 CppTimer::~CppTimer()
22 {
23     thread::id curThreadId = this_thread::get_id();
24     if (curThreadId != threadId) {
25         ILOG("CppTimer can not deleted by other thread!");
26     }
27 }
28 
Start(int64_t value)29 void CppTimer::Start(int64_t value)
30 {
31     thread::id curThreadId = this_thread::get_id();
32     if (curThreadId != threadId) {
33         ILOG("CppTimer can not started by other thread!");
34     }
35 
36     this->interval = value;
37     startTime = std::chrono::system_clock::now();
38     isRunning = true;
39 }
40 
Stop()41 void CppTimer::Stop()
42 {
43     thread::id curThreadId = this_thread::get_id();
44     if (curThreadId != threadId) {
45         ILOG("CppTimer can not stoped by other thread!");
46     }
47     isRunning = false;
48 }
49 
RunTimerTick(CallbackQueue & queue)50 void CppTimer::RunTimerTick(CallbackQueue& queue)
51 {
52     if (interval == 0) {
53         return;
54     }
55 
56     if (!isRunning) {
57         return;
58     }
59 
60     thread::id curThreadId = this_thread::get_id();
61     auto endTime = std::chrono::system_clock::now();
62 
63     if (curThreadId != threadId) {
64         ILOG("CppTimer can not run in other thread");
65         return;
66     }
67 
68     int64_t timePassed = duration_cast<chrono::milliseconds>(endTime - startTime).count();
69     if (timePassed < interval) {
70         return;
71     }
72 
73     if (shotTimes != 0) {
74         queue.AddCallback(functional);
75         startTime = endTime;
76     }
77 
78     if (shotTimes > 0) {
79         shotTimes--;
80     }
81 }
82