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;

  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  //用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::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> 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 = make_unique();

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 
#include 
#include 
#include 
#include 
#include 

using namespace std;

struct TimerNodeBase {
    time_t expire;
    int64_t id;
};

struct TimerNode : public TimerNodeBase {
    using Callback = std::function;
    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::steady_clock::now());
        auto temp = chrono::duration_cast(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(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> timermap;
};
int64_t Timer::gid = 0;


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

    unique_ptr timer = make_unique();

    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;
}

 

你可能感兴趣的:(数据结构,c++)