blob: 99df18b59b78f58474ce8f6f8c65be4c6faaf912 [file] [log] [blame]
Rolf Badorekef2bf512019-08-20 11:17:15 +03001/*
2 Copyright (c) 2018-2019 Nokia.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15*/
16
17#ifndef SHAREDDATALAYER_TIMER_HPP_
18#define SHAREDDATALAYER_TIMER_HPP_
19
20#include <map>
21#include <functional>
22#include <chrono>
23
24namespace shareddatalayer
25{
26 class Engine;
27 class TimerFD;
28
29 /**
30 * @brief One shot timer
31 *
32 * Timer is a one shot timer which expires once after being armed.
33 */
34 class Timer
35 {
36 public:
37 using Duration = std::chrono::steady_clock::duration;
38
39 using Callback = std::function<void()>;
40
41 /**
42 * Create a new timer. Each timer is associated with an Engine instance
43 * and the associated Engine instance must exist as long as the timer
44 * exists.
45 *
46 * @param engine The associated Engine instance.
47 */
48 explicit Timer(Engine& engine);
49
50 ~Timer();
51
52 /**
53 * Arm this timer. If already armed, then first disarm and then arm.
54 *
55 * @param duration Duration until this timer expires starting from
56 * <i>now</i>.
57 * @param cb Callback function to be called when this timer
58 * expires. The callback will not be called if this
59 * timer is disarmed or deleted before expiration.
60 *
61 * @see disarm
62 */
63 void arm(const Duration& duration, const Callback& cb);
64
65 /**
66 * Disarm this timer if armed. If not armed, then nothing is done.
67 *
68 * @see arm
69 */
70 void disarm();
71
72 /**
73 * Check if this timer is armed.
74 *
75 * @return <code>true</code>, if this timer is armed, otherwise
76 * <code>false</code>.
77 */
78 bool isArmed() const { return armed; }
79
80 Timer(Timer&&) = delete;
81 Timer(const Timer&) = delete;
82 Timer& operator = (Timer&&) = delete;
83 Timer& operator = (const Timer&) = delete;
84
85 private:
86 friend class TimerFD;
87
88 using Queue = std::multimap<Timer::Duration, std::pair<const Timer*, Timer::Callback>>;
89
90 Engine& engine;
91 bool armed;
92 /* The iterator is valid only while this timer is armed */
93 Queue::iterator iterator;
94 };
95}
96
97#endif