47 lines
1.1 KiB
C++
47 lines
1.1 KiB
C++
#ifndef _TIMER_HPP_
|
|
#define _TIMER_HPP_
|
|
|
|
#include <functional>
|
|
|
|
#ifndef ASIO_STANDALONE
|
|
#define ASIO_STANDALONE
|
|
#endif
|
|
#include <asio.hpp>
|
|
|
|
using timer_callback = std::function<void()>;
|
|
|
|
class Timer : public std::enable_shared_from_this<Timer> {
|
|
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>(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<Timer> AddTimer(const timer_callback& cb, uint32_t wait, uint32_t interval) = 0;
|
|
};
|
|
|
|
#endif
|