/** * * TimerQueue.h * An Tao * * Public header file in trantor lib. * * Copyright 2018, An Tao. All rights reserved. * Use of this source code is governed by a BSD-style license * that can be found in the License file. * * */ #pragma once #include "timer.h" #include #include #include #include #include namespace trantor { // class Timer; class EventLoop; class Channel; using TimerPtr = std::shared_ptr; struct TimerPtrComparer { bool operator()(const TimerPtr &x, const TimerPtr &y) const { return *x > *y; } }; class TimerQueue { protected: TimerQueue(const TimerQueue &) = delete; TimerQueue &operator=(const TimerQueue &) = delete; // some uncopyable classes maybe support move constructor.... TimerQueue(TimerQueue &&) noexcept(true) = default; TimerQueue &operator=(TimerQueue &&) noexcept(true) = default; public: explicit TimerQueue(EventLoop *loop); ~TimerQueue(); TimerId addTimer(const TimerCallback &cb, const TimePoint &when, const TimeInterval &interval); TimerId addTimer(TimerCallback &&cb, const TimePoint &when, const TimeInterval &interval); void addTimerInLoop(const TimerPtr &timer); void invalidateTimer(TimerId id); #ifdef __linux__ void reset(); #else int64_t getTimeout() const; void processTimers(); #endif protected: EventLoop *loop_; #ifdef __linux__ int timerfd_; std::shared_ptr timerfdChannelPtr_; void handleRead(); #endif std::priority_queue, TimerPtrComparer> timers_; bool callingExpiredTimers_; bool insert(const TimerPtr &timePtr); std::vector getExpired(); void reset(const std::vector &expired, const TimePoint &now); std::vector getExpired(const TimePoint &now); private: std::unordered_set timerIdSet_; }; } // namespace trantor