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