毫秒级定时器模块的设计与实现

  定时器在服务器的通信模块中会广泛使用到,通过定时器可以相应的高效实现业务逻辑。由于一般给出的定时器都是以秒作为最小单元来处理的,大部分场景能够满足要求,但在一些特殊场景需要实现更精确的定时任务,这时候,就有必要去构建一个毫秒级的定时管理模块。因而本文分享了一种定时器管理模块的实现方法,同时给出了相应的使用案例,希望对读者有一定的帮助。

1、毫秒级的时间类型
  首先构建一个毫秒级的类型,并对相应的运算符进行了重载,具体代码示例如下:

#ifdef LINUX #include <sys/time.h> #endif #ifdef IOS #include <sys/_types/_timeval.h> #endif #ifdef WIN32 #include <winsock.h> #endif class Time { private: struct timeval time_val; public: Time(); ~Time(); Time(const Time& other); Time(const struct timeval& timeVal); Time& operator=(const Time& other); Time& operator=(const struct timeval& timeVal); bool operator==(const Time& other); bool operator<(const Time& other); Time& operator+=(int val); time_t getSecond(); } Time::Time() { memset(time_val, 0, sizeof(struct timeval)); } Time::Time(const Time& other) { time_val = other.time_val; } Time::Time(const struct timeval& timeVal) { time_val = timeVal; } Time& operator=(const Time& other) { time_val = other.time_val; return *this; } Time& operator=(const struct timeval& timeVal) { time_val = timeVal; return *this; } bool operator==(const Time& other) { if (time_val.tv_sec != other.time_val.tv_sec || time_val.tv_usec != other.time_val.tv_usec ) { return false; } return true; } bool operator<(const Time& other) { if (time_val.tv_sec < other.time_val.tv_sec) { return true; } else if (time_val.tv_sec == other.time_val.tv_sec) { if (time_val.tv_usec < other.time_val.tv_usec) { return true; } } return false; } Time& operator+=(int val) { time_val.tv_usec += val*1000; time_val.tv_sec += time_val.tv_usec/1000000; time_val.tv_usec = time_val.tv_usec % 1000000; } time_t getSecond() { return time_val.tv_sec; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zygffw.html