12a18e699SShuo Chen// excerpts from http://code.google.com/p/muduo/ 22a18e699SShuo Chen// 32a18e699SShuo Chen// Use of this source code is governed by a BSD-style license 42a18e699SShuo Chen// that can be found in the License file. 52a18e699SShuo Chen// 62a18e699SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 72a18e699SShuo Chen 82a18e699SShuo Chen#ifndef MUDUO_NET_TIMERQUEUE_H 92a18e699SShuo Chen#define MUDUO_NET_TIMERQUEUE_H 102a18e699SShuo Chen 112a18e699SShuo Chen#include <set> 122a18e699SShuo Chen#include <vector> 132a18e699SShuo Chen 142a18e699SShuo Chen#include <boost/noncopyable.hpp> 152a18e699SShuo Chen 162a18e699SShuo Chen#include "datetime/Timestamp.h" 172a18e699SShuo Chen#include "thread/Mutex.h" 182a18e699SShuo Chen#include "Callbacks.h" 192a18e699SShuo Chen#include "Channel.h" 202a18e699SShuo Chen 212a18e699SShuo Chennamespace muduo 222a18e699SShuo Chen{ 232a18e699SShuo Chen 242a18e699SShuo Chenclass EventLoop; 252a18e699SShuo Chenclass Timer; 262a18e699SShuo Chenclass TimerId; 272a18e699SShuo Chen 282a18e699SShuo Chen/// 292a18e699SShuo Chen/// A best efforts timer queue. 302a18e699SShuo Chen/// No guarantee that the callback will be on time. 312a18e699SShuo Chen/// 322a18e699SShuo Chenclass TimerQueue : boost::noncopyable 332a18e699SShuo Chen{ 342a18e699SShuo Chen public: 352a18e699SShuo Chen TimerQueue(EventLoop* loop); 362a18e699SShuo Chen ~TimerQueue(); 372a18e699SShuo Chen 382a18e699SShuo Chen /// 392a18e699SShuo Chen /// Schedules the callback to be run at given time, 402a18e699SShuo Chen /// repeats if @c interval > 0.0. 412a18e699SShuo Chen /// 422a18e699SShuo Chen /// Must be thread safe. Usually be called from other threads. 432a18e699SShuo Chen TimerId addTimer(const TimerCallback& cb, 442a18e699SShuo Chen Timestamp when, 452a18e699SShuo Chen double interval); 462a18e699SShuo Chen 472a18e699SShuo Chen // void cancel(TimerId timerId); 482a18e699SShuo Chen 492a18e699SShuo Chen private: 502a18e699SShuo Chen 512a18e699SShuo Chen // FIXME: use unique_ptr<Timer> instead of raw pointers. 522a18e699SShuo Chen typedef std::pair<Timestamp, Timer*> Entry; 532a18e699SShuo Chen typedef std::set<Entry> TimerList; 542a18e699SShuo Chen 55344a2ce1SShuo Chen void addTimerInLoop(Timer* timer); 56dee5abbcSShuo Chen // called when timerfd alarms 572a18e699SShuo Chen void handleRead(); 582a18e699SShuo Chen // move out all expired timers 592a18e699SShuo Chen std::vector<Entry> getExpired(Timestamp now); 602a18e699SShuo Chen void reset(const std::vector<Entry>& expired, Timestamp now); 612a18e699SShuo Chen 622a18e699SShuo Chen bool insert(Timer* timer); 632a18e699SShuo Chen 642a18e699SShuo Chen EventLoop* loop_; 652a18e699SShuo Chen const int timerfd_; 662a18e699SShuo Chen Channel timerfdChannel_; 672a18e699SShuo Chen // Timer list sorted by expiration 682a18e699SShuo Chen TimerList timers_; 692a18e699SShuo Chen}; 702a18e699SShuo Chen 712a18e699SShuo Chen} 722a18e699SShuo Chen#endif // MUDUO_NET_TIMERQUEUE_H 73