#ifndef _TIMER_HPP_ #define _TIMER_HPP_ #include #ifndef ASIO_STANDALONE #define ASIO_STANDALONE #endif #include using timer_callback = std::function; class Timer : public std::enable_shared_from_this { public: Timer(asio::io_context& ctx, const timer_callback& cb, uint32_t wait, uint32_t interval) : callback(cb), interval(interval), timer(ctx, asio::chrono::milliseconds(wait)) {} void Begin() { timer.async_wait([this, self = shared_from_this()](const asio::error_code& ec) { if(ec) return; if(callback) callback(); if(interval > 0) std::make_shared(timer.get_io_context(), callback, interval, interval)->Begin(); }); } void Cancel() { timer.cancel(); } protected: timer_callback callback; uint32_t interval; asio::steady_timer timer; }; class TimerService { public: virtual std::weak_ptr AddTimer(const timer_callback& cb, uint32_t wait, uint32_t interval) = 0; }; #endif