19a1e991dSShuo Chen// excerpts from http://code.google.com/p/muduo/ 29a1e991dSShuo Chen// 39a1e991dSShuo Chen// Use of this source code is governed by a BSD-style license 49a1e991dSShuo Chen// that can be found in the License file. 59a1e991dSShuo Chen// 69a1e991dSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 79a1e991dSShuo Chen 89a1e991dSShuo Chen#ifndef MUDUO_NET_TIMERQUEUE_H 99a1e991dSShuo Chen#define MUDUO_NET_TIMERQUEUE_H 109a1e991dSShuo Chen 119a1e991dSShuo Chen#include <set> 129a1e991dSShuo Chen#include <vector> 139a1e991dSShuo Chen 149a1e991dSShuo Chen#include <boost/noncopyable.hpp> 159a1e991dSShuo Chen 169a1e991dSShuo Chen#include "datetime/Timestamp.h" 179a1e991dSShuo Chen#include "thread/Mutex.h" 189a1e991dSShuo Chen#include "Callbacks.h" 199a1e991dSShuo Chen#include "Channel.h" 209a1e991dSShuo Chen 219a1e991dSShuo Chennamespace muduo 229a1e991dSShuo Chen{ 239a1e991dSShuo Chen 249a1e991dSShuo Chenclass EventLoop; 259a1e991dSShuo Chenclass Timer; 269a1e991dSShuo Chenclass TimerId; 279a1e991dSShuo Chen 289a1e991dSShuo Chen/// 299a1e991dSShuo Chen/// A best efforts timer queue. 309a1e991dSShuo Chen/// No guarantee that the callback will be on time. 319a1e991dSShuo Chen/// 329a1e991dSShuo Chenclass TimerQueue : boost::noncopyable 339a1e991dSShuo Chen{ 349a1e991dSShuo Chen public: 359a1e991dSShuo Chen TimerQueue(EventLoop* loop); 369a1e991dSShuo Chen ~TimerQueue(); 379a1e991dSShuo Chen 389a1e991dSShuo Chen /// 399a1e991dSShuo Chen /// Schedules the callback to be run at given time, 409a1e991dSShuo Chen /// repeats if @c interval > 0.0. 419a1e991dSShuo Chen /// 429a1e991dSShuo Chen /// Must be thread safe. Usually be called from other threads. 439a1e991dSShuo Chen TimerId addTimer(const TimerCallback& cb, 449a1e991dSShuo Chen Timestamp when, 459a1e991dSShuo Chen double interval); 469a1e991dSShuo Chen 479a1e991dSShuo Chen // void cancel(TimerId timerId); 489a1e991dSShuo Chen 499a1e991dSShuo Chen private: 509a1e991dSShuo Chen 519a1e991dSShuo Chen // FIXME: use unique_ptr<Timer> instead of raw pointers. 529a1e991dSShuo Chen typedef std::pair<Timestamp, Timer*> Entry; 539a1e991dSShuo Chen typedef std::set<Entry> TimerList; 549a1e991dSShuo Chen 55344a2ce1SShuo Chen void addTimerInLoop(Timer* timer); 56dee5abbcSShuo Chen // called when timerfd alarms 579a1e991dSShuo Chen void handleRead(); 589a1e991dSShuo Chen // move out all expired timers 599a1e991dSShuo Chen std::vector<Entry> getExpired(Timestamp now); 609a1e991dSShuo Chen void reset(const std::vector<Entry>& expired, Timestamp now); 619a1e991dSShuo Chen 629a1e991dSShuo Chen bool insert(Timer* timer); 639a1e991dSShuo Chen 649a1e991dSShuo Chen EventLoop* loop_; 659a1e991dSShuo Chen const int timerfd_; 669a1e991dSShuo Chen Channel timerfdChannel_; 679a1e991dSShuo Chen // Timer list sorted by expiration 689a1e991dSShuo Chen TimerList timers_; 699a1e991dSShuo Chen}; 709a1e991dSShuo Chen 719a1e991dSShuo Chen} 729a1e991dSShuo Chen#endif // MUDUO_NET_TIMERQUEUE_H 73