TimerQueue.h revision dee5abbc
142bf2220SShuo Chen// excerpts from http://code.google.com/p/muduo/ 242bf2220SShuo Chen// 342bf2220SShuo Chen// Use of this source code is governed by a BSD-style license 442bf2220SShuo Chen// that can be found in the License file. 542bf2220SShuo Chen// 642bf2220SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 742bf2220SShuo Chen 842bf2220SShuo Chen#ifndef MUDUO_NET_TIMERQUEUE_H 942bf2220SShuo Chen#define MUDUO_NET_TIMERQUEUE_H 1042bf2220SShuo Chen 1142bf2220SShuo Chen#include <set> 1242bf2220SShuo Chen#include <vector> 1342bf2220SShuo Chen 1442bf2220SShuo Chen#include <boost/noncopyable.hpp> 1542bf2220SShuo Chen 1642bf2220SShuo Chen#include "datetime/Timestamp.h" 1742bf2220SShuo Chen#include "thread/Mutex.h" 1842bf2220SShuo Chen#include "Callbacks.h" 1942bf2220SShuo Chen#include "Channel.h" 2042bf2220SShuo Chen 2142bf2220SShuo Chennamespace muduo 2242bf2220SShuo Chen{ 2342bf2220SShuo Chen 2442bf2220SShuo Chenclass EventLoop; 2542bf2220SShuo Chenclass Timer; 2642bf2220SShuo Chenclass TimerId; 2742bf2220SShuo Chen 2842bf2220SShuo Chen/// 2942bf2220SShuo Chen/// A best efforts timer queue. 3042bf2220SShuo Chen/// No guarantee that the callback will be on time. 3142bf2220SShuo Chen/// 3242bf2220SShuo Chenclass TimerQueue : boost::noncopyable 3342bf2220SShuo Chen{ 3442bf2220SShuo Chen public: 3542bf2220SShuo Chen TimerQueue(EventLoop* loop); 3642bf2220SShuo Chen ~TimerQueue(); 3742bf2220SShuo Chen 3842bf2220SShuo Chen /// 3942bf2220SShuo Chen /// Schedules the callback to be run at given time, 4042bf2220SShuo Chen /// repeats if @c interval > 0.0. 4142bf2220SShuo Chen /// 4242bf2220SShuo Chen /// Must be thread safe. Usually be called from other threads. 4342bf2220SShuo Chen TimerId addTimer(const TimerCallback& cb, 4442bf2220SShuo Chen Timestamp when, 4542bf2220SShuo Chen double interval); 4642bf2220SShuo Chen 4742bf2220SShuo Chen // void cancel(TimerId timerId); 4842bf2220SShuo Chen 4942bf2220SShuo Chen private: 5042bf2220SShuo Chen 5142bf2220SShuo Chen // FIXME: use unique_ptr<Timer> instead of raw pointers. 5242bf2220SShuo Chen typedef std::pair<Timestamp, Timer*> Entry; 5342bf2220SShuo Chen typedef std::set<Entry> TimerList; 5442bf2220SShuo Chen 55dee5abbcSShuo Chen // called when timerfd alarms 5642bf2220SShuo Chen void handleRead(); 5742bf2220SShuo Chen // move out all expired timers 5842bf2220SShuo Chen std::vector<Entry> getExpired(Timestamp now); 5942bf2220SShuo Chen void reset(const std::vector<Entry>& expired, Timestamp now); 6042bf2220SShuo Chen 6142bf2220SShuo Chen bool insert(Timer* timer); 6242bf2220SShuo Chen 6342bf2220SShuo Chen EventLoop* loop_; 6442bf2220SShuo Chen const int timerfd_; 6542bf2220SShuo Chen Channel timerfdChannel_; 6642bf2220SShuo Chen // Timer list sorted by expiration 6742bf2220SShuo Chen TimerList timers_; 6842bf2220SShuo Chen}; 6942bf2220SShuo Chen 7042bf2220SShuo Chen} 7142bf2220SShuo Chen#endif // MUDUO_NET_TIMERQUEUE_H 72