Dobby 3.0
Dobby “Docker based Thingy” is a tool for managing and running OCI containers using crun
Loading...
Searching...
No Matches
Timer.h
1/*
2* If not stated otherwise in this file or this component's LICENSE file the
3* following copyright and licenses apply:
4*
5* Copyright 2020 Sky UK
6*
7* Licensed under the Apache License, Version 2.0 (the "License");
8* you may not use this file except in compliance with the License.
9* You may obtain a copy of the License at
10*
11* http://www.apache.org/licenses/LICENSE-2.0
12*
13* Unless required by applicable law or agreed to in writing, software
14* distributed under the License is distributed on an "AS IS" BASIS,
15* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16* See the License for the specific language governing permissions and
17* limitations under the License.
18*/
19/*
20 * File: Timer.h
21 * Author: jarek.dziedzic@bskyb.com
22 *
23 * Created on 29 May 2015
24 */
25
26#ifndef AICOMMON_TIMER_H
27#define AICOMMON_TIMER_H
28
29#include "Mutex.h"
30#include "ConditionVariable.h"
31
32#include <chrono>
33#include <thread>
34#include <functional>
35
36namespace AICommon
37{
38 enum class TimerType
39 {
40 OneRun = 0,
41 Recurring = 1
42 };
43
44 enum class TimerThreadPriority
45 {
46 Default,
47 Low
48 };
49
50
51 class Timer
52 {
53
54 public:
64 template<typename F, typename... Args>
65 Timer(const std::chrono::milliseconds &timeout, F f, Args&&... args)
66 {
67 start(timeout, TimerType::OneRun, TimerThreadPriority::Default, std::bind(f, args...));
68 }
69
70 template<typename F, typename... Args>
71 Timer(const std::chrono::milliseconds &timeout, TimerType type, TimerThreadPriority prio, F f, Args&&... args)
72 {
73 start(timeout, type, prio, std::bind(f, args...));
74 }
75
76 Timer(Timer&& other) = delete;
77 Timer(const Timer&) = delete;
78
79 Timer& operator=(Timer&& other) = delete;
80 Timer& operator=(const Timer& other) = delete;
81
86 ~Timer();
87
93 void cancel();
94
95
96 private:
97 void start(const std::chrono::milliseconds &timeout, TimerType type, TimerThreadPriority prio, const std::function<void()> &callback);
98
99 void singleShotTimer(TimerThreadPriority prio, const std::chrono::steady_clock::time_point &deadline);
100 void recurringTimer(TimerThreadPriority prio, const std::chrono::milliseconds &interval);
101
102 private:
103 std::function<void()> mCallback;
104
105 std::thread mTimerThread;
106 Mutex mLock;
107 ConditionVariable mCond;
108 bool mCancel;
109
110 };
111
112} // namespace AICommon
113
114#endif // !defined(AICOMMON_TIMER_H)
115
Definition Timer.h:52
~Timer()
The destructor cancels the timer if it's still not expired.
Definition Timer.cpp:33
void cancel()
Cancels the timer.
Definition Timer.cpp:61
Timer(const std::chrono::milliseconds &timeout, F f, Args &&... args)
Starts a timer that will expire after timeout and execute action.
Definition Timer.h:65