1b37003a7SShuo Chen// excerpts from http://code.google.com/p/muduo/ 2b37003a7SShuo Chen// 3b37003a7SShuo Chen// Use of this source code is governed by a BSD-style license 4b37003a7SShuo Chen// that can be found in the License file. 5b37003a7SShuo Chen// 6b37003a7SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 7b37003a7SShuo Chen 8b37003a7SShuo Chen#ifndef MUDUO_NET_TIMERQUEUE_H 9b37003a7SShuo Chen#define MUDUO_NET_TIMERQUEUE_H 10b37003a7SShuo Chen 11b37003a7SShuo Chen#include <set> 12b37003a7SShuo Chen#include <vector> 13b37003a7SShuo Chen 14b37003a7SShuo Chen#include <boost/noncopyable.hpp> 15b37003a7SShuo Chen 16b37003a7SShuo Chen#include "datetime/Timestamp.h" 17b37003a7SShuo Chen#include "thread/Mutex.h" 18b37003a7SShuo Chen#include "Callbacks.h" 19b37003a7SShuo Chen#include "Channel.h" 20b37003a7SShuo Chen 21b37003a7SShuo Chennamespace muduo 22b37003a7SShuo Chen{ 23b37003a7SShuo Chen 24b37003a7SShuo Chenclass EventLoop; 25b37003a7SShuo Chenclass Timer; 26b37003a7SShuo Chenclass TimerId; 27b37003a7SShuo Chen 28b37003a7SShuo Chen/// 29b37003a7SShuo Chen/// A best efforts timer queue. 30b37003a7SShuo Chen/// No guarantee that the callback will be on time. 31b37003a7SShuo Chen/// 32b37003a7SShuo Chenclass TimerQueue : boost::noncopyable 33b37003a7SShuo Chen{ 34b37003a7SShuo Chen public: 35b37003a7SShuo Chen TimerQueue(EventLoop* loop); 36b37003a7SShuo Chen ~TimerQueue(); 37b37003a7SShuo Chen 38b37003a7SShuo Chen /// 39b37003a7SShuo Chen /// Schedules the callback to be run at given time, 40b37003a7SShuo Chen /// repeats if @c interval > 0.0. 41b37003a7SShuo Chen /// 42b37003a7SShuo Chen /// Must be thread safe. Usually be called from other threads. 43b37003a7SShuo Chen TimerId addTimer(const TimerCallback& cb, 44b37003a7SShuo Chen Timestamp when, 45b37003a7SShuo Chen double interval); 46b37003a7SShuo Chen 47b37003a7SShuo Chen // void cancel(TimerId timerId); 48b37003a7SShuo Chen 49b37003a7SShuo Chen private: 50b37003a7SShuo Chen 51b37003a7SShuo Chen // FIXME: use unique_ptr<Timer> instead of raw pointers. 52b37003a7SShuo Chen typedef std::pair<Timestamp, Timer*> Entry; 53b37003a7SShuo Chen typedef std::set<Entry> TimerList; 54b37003a7SShuo Chen 55344a2ce1SShuo Chen void addTimerInLoop(Timer* timer); 56dee5abbcSShuo Chen // called when timerfd alarms 57b37003a7SShuo Chen void handleRead(); 58b37003a7SShuo Chen // move out all expired timers 59b37003a7SShuo Chen std::vector<Entry> getExpired(Timestamp now); 60b37003a7SShuo Chen void reset(const std::vector<Entry>& expired, Timestamp now); 61b37003a7SShuo Chen 62b37003a7SShuo Chen bool insert(Timer* timer); 63b37003a7SShuo Chen 64b37003a7SShuo Chen EventLoop* loop_; 65b37003a7SShuo Chen const int timerfd_; 66b37003a7SShuo Chen Channel timerfdChannel_; 67b37003a7SShuo Chen // Timer list sorted by expiration 68b37003a7SShuo Chen TimerList timers_; 69b37003a7SShuo Chen}; 70b37003a7SShuo Chen 71b37003a7SShuo Chen} 72b37003a7SShuo Chen#endif // MUDUO_NET_TIMERQUEUE_H 73