1 //******************************************************************
3 // Copyright 2015 Samsung Electronics All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 #ifndef _EXPIRY_TIMER_IMPL_H_
22 #define _EXPIRY_TIMER_IMPL_H_
29 #include <condition_variable>
31 #include <unordered_set>
43 typedef unsigned int Id;
44 typedef std::function< void(Id) > Callback;
46 typedef long long DelayInMillis;
49 typedef std::chrono::milliseconds Milliseconds;
55 ExpiryTimerImpl(const ExpiryTimerImpl&) = delete;
56 ExpiryTimerImpl& operator=(const ExpiryTimerImpl&) = delete;
59 static ExpiryTimerImpl* getInstance();
61 std::shared_ptr< TimerTask > post(DelayInMillis, Callback);
64 size_t cancelAll(const std::unordered_set< std::shared_ptr<TimerTask > >&);
67 static Milliseconds convertToTime(Milliseconds);
69 std::shared_ptr< TimerTask > addTask(Milliseconds, Callback, Id);
72 * @pre The lock must be acquired with m_mutex.
74 bool containsId(Id) const;
78 * @pre The lock must be acquired with m_mutex.
80 void executeExpired();
83 * @pre The lock must be acquired with m_mutex.
85 Milliseconds remainingTimeForNext() const;
90 std::multimap< Milliseconds, std::shared_ptr< TimerTask > > m_tasks;
94 std::condition_variable m_cond;
98 std::uniform_int_distribution< Id > m_dist;
105 TimerTask(ExpiryTimerImpl::Id, ExpiryTimerImpl::Callback);
107 TimerTask(const TimerTask&) = delete;
108 TimerTask(TimerTask&&) = delete;
110 TimerTask& operator=(const TimerTask&) = delete;
111 TimerTask& operator=(TimerTask&&) = delete;
113 bool isExecuted() const;
114 ExpiryTimerImpl::Id getId() const;
120 std::atomic< ExpiryTimerImpl::Id > m_id;
121 ExpiryTimerImpl::Callback m_callback;
123 friend class ExpiryTimerImpl;
128 #endif //_EXPIRY_TIMER_IMPL_H_