C++定时器

定时器:管理大量延时任务的模块,异步任务

addTimer(1000, func);

addTimer(1000, func);

addTimer(1000, func);

addTimer(1000, func);

数据结构: 有序结构, 增删改后仍然有序

                  最近要被触发的定时任务

      可用:set/map/multiset/multiset/

                 跳表skiplist

                 时间轮

      

触发机制: 不要占用线程或者系统性能(sleep)

任务如何组织?

C语言:

struct TimerNode {

  time_t expire;//not unique

   callback func;

  void* ctx;//args

};

C++11:

struct TimerNode {

  time_t expire;//not unique

  uint64_t id;//用于set数据结构

  using callback = std::function<void(const TimerNode&)>;

  callback func;

};

优化

=====》

struct TimerNodeBase {

  time_t expire;//not unique

  uint64_t id;//用于set数据结

};

struct TimerNode : public TimerNodeBase  {

  callback func;//函数对象,拷贝成本高,所以通过继承现剥离

  TimerNode(int times, int i, callback f) : expire:(times), func(f) , id(i) {}

};

-===》 std::set<TimerNode >  //用object而不是指针,为了简化,不用单独维护指针

//借助C++14 等价key

bool operator<(const TimerNodeBase &, const TimerNodeBase &) {

  if (l.expire < r.expire)

return true;

else if (l.expire > r.expire)

  return false;

else

  return l.id < r.id;

}

class Timer {

public:

 static inline time_t GetTicks() {

//返回最近的系统启动时间到当前时间,单位ms,

return std::chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now().time_since_epoch()).count();

//这里用steady_clock而不是system_clock是因为前者在修改系统时间不受影响

}

TimerNodeBase  AddTimer(int msec, callback func) {

  time_t exp = GetTick() + msec;

auto pairs = timeouts.emplace(exp, GetId(), func); 

return (TimerNodeBase)*pairs.first;

}

void DelTimer(TimerNodeBase node) {

auto iter = timesout.find(node);

if (iter != timesout.end())

  timesout.erase(iter);

}

 private:

static inline uint64_t GetId() {

return gid++;

}

static uint64_t gid;

set<TimerNode, std::less<>> timeouts;

};

timerfd   linux  2.6 内核用fd来管理定时器

  creat timerfd

方式: 

1 read(fd);

2. epoll  //检测time事件

int main() {

int epfd = epoll_create(1);//大于0即可

int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);

//注册事件

struct epoll_event ev = {.events= EPOLLIN | EPOLLET};//EPOLLET:edge trigger,only once边缘触发

epoll_ctl(epfd, EPOLL_CTL_ADD, timerfd, &ev);

  //用unique ptr实现单例

unique_ptr<Timer> timer = make_unique<Timer>();

int i = 0;

timer->AddTimer(1000, [&](const TimerNode& node) {

});

//事件检测流程

struct epoll_event  evs[64] = {0};

while (1) {

int n = epoll_wait(epfd, evs, 64, -1);

/handle timer

}

}

完整代码如下:

#include <sys/epoll.h>
#include <functional>
#include <chrono>
#include <set>
#include <memory>
#include <iostream>

using namespace std;

struct TimerNodeBase {
    time_t expire;
    int64_t id;
};

struct TimerNode : public TimerNodeBase {
    using Callback = std::function<void(const TimerNode &node)>;
    Callback func;
};

bool operator < (const TimerNodeBase &lhd, const TimerNodeBase &rhd) {
    if (lhd.expire < rhd.expire)
        return true;
    else if (lhd.expire > rhd.expire) 
        return false;
    return lhd.id < rhd.id;
}

class Timer {
public:
    static time_t GetTick() {
        auto sc = chrono::time_point_cast<chrono::milliseconds>(chrono::steady_clock::now());
        auto temp = chrono::duration_cast<chrono::milliseconds>(sc.time_since_epoch());
        return temp.count();
    }
    static int64_t GenID() {
        return ++gid;
    }
    TimerNodeBase AddTimer(time_t msec, TimerNode::Callback func) {
        TimerNode tnode;
        tnode.expire = GetTick() + msec;
        tnode.func = func;
        tnode.id = GenID();
        timermap.insert(tnode);
        return static_cast<TimerNodeBase>(tnode);
    }
    bool DelTimer(TimerNodeBase &node) {
        auto iter = timermap.find(node);
        if (iter != timermap.end()) {
            timermap.erase(iter);
            return true;
        }
        return false;
    }

    bool CheckTimer() {
        auto iter = timermap.begin();
        if (iter != timermap.end() && iter->expire <= GetTick()) {
            iter->func(*iter);
            timermap.erase(iter);
            return true;
        }
        return false;
    }

    time_t TimeToSleep() {
        auto iter = timermap.begin();
        if (iter == timermap.end()) {
            return -1;
        }
        time_t diss = iter->expire-GetTick();
        return diss > 0 ? diss : 0;
    }
private:
    static int64_t gid;
    set<TimerNode, std::less<>> timermap;
};
int64_t Timer::gid = 0;


int main() {
    int epfd = epoll_create(1);

    unique_ptr<Timer> timer = make_unique<Timer>();

    int i =0;
    timer->AddTimer(1000, [&](const TimerNode &node) {
        cout << Timer::GetTick() << "node id:" << node.id << " revoked times:" << ++i << endl;
    });

    timer->AddTimer(1000, [&](const TimerNode &node) {
        cout << Timer::GetTick() << "node id:" << node.id << " revoked times:" << ++i << endl;
    });

    timer->AddTimer(3000, [&](const TimerNode &node) {
        cout << Timer::GetTick() << "node id:" << node.id << " revoked times:" << ++i << endl;
    });

    auto node = timer->AddTimer(2100, [&](const TimerNode &node) {
        cout << Timer::GetTick() << "node id:" << node.id << " revoked times:" << ++i << endl;
    });

    timer->DelTimer(node);

    cout << "now time:" << Timer::GetTick() << endl;
    epoll_event ev[64] = {0};

    while (true) {
        /*
            -1 永久阻塞
            0 没有事件立刻返回,有事件就拷贝到 ev 数组当中
            t > 0  阻塞等待 t ms, 
            timeout  最近触发的定时任务离当前的时间
        */
        int n = epoll_wait(epfd, ev, 64, timer->TimeToSleep());
        for (int i = 0; i < n; i++) {
            /**/
        }
        /* 处理定时事件*/
        while(timer->CheckTimer());
    }
    
    return 0;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Poo_Chai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值