用C++11实现一个定时器

#include <iostream>
#include <queue>
#include <memory>
#include <vector>
#include <functional>
#include <chrono>
#include <thread>
#include <mutex>
#include <unistd.h>
#include <sys/time.h>

#define NOW (std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now().time_since_epoch()))

class Timer 
{
private:
    std::mutex lk_;
private:
    struct TimerEvent {
        TimerEvent(const std::chrono::microseconds &tp, const std::function<void()> &cb) {
            timePoint = tp;
            callback = cb; 
        }
        
        std::chrono::microseconds timePoint; //us 
        std::function<void()> callback; 
        bool operator<(const TimerEvent& other) const {
            return timePoint > other.timePoint;
        }
        bool operator>(const TimerEvent& other) const {
            return timePoint < other.timePoint;
        }
    };

    std::priority_queue<TimerEvent> events;

public: 
    void schedule(const int64_t delayus, const std::function<void()> &callback)
    {
        std::lock_guard<std::mutex> lg(lk_);
        auto point = NOW + std::chrono::microseconds(delayus);
        events.emplace(TimerEvent(point, callback));
    }
    
    void run() {
        while (true) {
            while (!events.empty()) {
                auto head = events.top();
                if (head.timePoint <= NOW) {
                    head.callback();
                    std::lock_guard<std::mutex> lg(lk_);
                    events.pop();
                } else {
                    int64_t value = (head.timePoint - NOW).count();
                    if (value > 0) {
                        usleep(value);
                    } else {
                        head.callback();
                        std::lock_guard<std::mutex> lg(lk_);
                        events.pop();
                    }
                }
            }
            sleep(0);
        }
    }
};

void exampleCallback() {
    std::cout << "Timer event triggered!" << std::endl;
}

int main() {
    Timer timer;

    timer.schedule(1000000, exampleCallback);
    timer.schedule(500000, exampleCallback);
    timer.schedule(200000, exampleCallback);
    timer.schedule(20000000, exampleCallback);

    std::cout << "Microsecond timer started. Waiting for events..." << std::endl;
    timer.run();

    return 0;
}

运行结果:
Microsecond timer started. Waiting for events…
Timer event triggered!
Timer event triggered!
Timer event triggered!
Timer event triggered!
^C

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值