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