定时器设计实现

描述

由于目前C++标准中没有现成的定时器,本设计使用C++11相关语法并进行封装。

本定时器包含一个TimerManager类用于创建定时器和进行定时任务管理,TimerManager会创建两个线程(mTimerTickThread、mTimerCallbackThread)分别用于时间处理和函数回调。

可以使用TimerManager的create方法创建多个定时器,每次创建的定时器ID会累加,并返回ITimer类型的共享指针。其中ITimer类中定义了start和stop方法,用于启动或停止当前定时器。

TimerManager还有一个内部类TimerMessageQueue用于实现定时器消息的插入、删除与定时控制。

关键类型及接口介绍

TimerMessage类型作为通信的元素类型

using TimerCallback = std::function;

struct TimerMessage {
const int id; // time id.
const long long timeout; // time out value.
const TimerCallback callback; // timeout callback function.
const TimerType type; // 0:once, 1:periodic.
long long when; // time out occure time.
bool valid; // set true when timeout and pop from message queue.

TimerMessage()
: id(0), timeout(0), callback(nullptr), type(ONCE_TIMER), when(0), valid(false)
{}

TimerMessage(const int &id, const long long &timeout, const TimerCallback &callback,
const TimerType &type = ONCE_TIMER)
: id(id), timeout(timeout), callback(callback), type(type), when(0), valid(false)
{}
};()>

id、timeout、callback、type伴随着timer的生命周期,一旦创建不可修改。
when、valid为辅助信息,在消息流转过程中适时变化。

TimerManager的create方法

std::shared_ptr create(const long long &timeoutMillis, const TimerCallback &callback,
const TimerType &type = TIMERTYPE_ONCE);

用于创建定时器,有三个参数,分别是定时时长(单位毫秒),超时callback用于定时器到期的回调函数,定时器类型(单次还是循环定时器)。

定时器类的start、stop方法

bool start(void);
void stop(void);

start时会向TimerMessageQueue中插入消息,该消息包括定时器id、超时时间timeout、回调函数callback、定时器类型type、到期时间when,插入时按when进行排序(二分法、复杂度为log2N);

stop时会依据id从TimerMessageQueue中删除消息,并将valid设置为false,防止继续callback;

在重复start时会先stop原来的定时器再重新start,到期时间以最后一次start的时间为准。

核心逻辑介绍

TimerMessageQueue的插入与删除实现,确保消息能高效的按序插入对应位置。

bool enqueueMessage(const TimerMessageRefPtr &message, const long long &when)
{
do {
std::lock_guard lg(mMuxLock);
mMapIdWhens[message->id].push_back(when);
LOGD("add message id:%d, when:%lld", message->id, when);
message->when = when;
mMessages.insert(
std::upper_bound(mMessages.begin(), mMessages.end(), when,
[](const long long &when, const TimerMessageRefPtr &m) {
return (when < m->when);
}),
message);
} while (0);

mCond.notify_one();
std::this_thread::yield();
return true;
}

void removeMessages(const int &id)
{
std::lock_guard lg(mMuxLock);
auto it = mMapIdWhens.find(id);
if (it == mMapIdWhens.end()) {
return;
}
for (auto const &when : it->second) {
LOGD("del message id:%d, when:%lld", id, when);
mMessages.erase(
std::remove_if(
std::lower_bound(mMessages.begin(), mMessages.end(), when,
[](const TimerMessageRefPtr &m, const long long &when) {
return (m->when < when);
}),
std::upper_bound(mMessages.begin(), mMessages.end(), when,
[](const long long &when, const TimerMessageRefPtr &m) {
return (when < m->when);
}),
[&id](const TimerMessageRefPtr &m) { return ((id == m->id)); }),
mMessages.end());
}
mMapIdWhens.erase(id);
}

bool hasMessages(const int &id) const
{
std::lock_guard lg(mMuxLock);
bool ret = (mMapIdWhens.end() != mMapIdWhens.find(id));
LOGV("has message id:%d %s", id, ret ? "yes" : "no");
return ret;
}

std::lower_bound和std::upper_bound用于在有序的容器中快速查找可插入位置(不小于目标值和不大于目标值的位置)迭代器。

取出定时器到期消息

mTimerTickThread用于从mTimerTickQueue中取出到期的定时器消息。

如果没有到期消息则会休眠等待,等待的时间是最近要到期的时间与当前时间差,并且可以随时被打断(当有新的消息插入时会打断);

由于消息插入时是按到期时间排序插入的,所以每次取出的都是最近要到期的那一条定时消息。

inline void waitForItems(void)
{
std::unique_lock ul(mMuxLock);
mCond.wait(ul, [this]() { return !mMessages.empty(); });
if (0 == mMessages.front()->when) {
return;
}

long long waitingTimeMicros = 0;
while (!mMessages.empty()
&& (waitingTimeMicros = mMessages.front()->when - steadyTimeMicros()) > 0) {
// next message is not ready, set a timeout to wake up when it is ready.
mCond.wait_for(ul, std::chrono::microseconds(waitingTimeMicros));
}
}

inline TimerMessageRefPtr next(void)
{
while (true) {
waitForItems();
do {
std::lock_guard lg(mMuxLock); // minimise the lock scope.
if (!mMessages.empty()
&& (steadyTimeMicros() >= mMessages.front()->when)) { // time is up.
TimerMessageRefPtr msg = std::move(mMessages.front());
mMessages.pop_front();
msg->valid = true;

// remove message by id and when from map.
auto &whens = mMapIdWhens[msg->id];
whens.erase(std::remove_if(whens.begin(), whens.end(),
[&msg](const long long &when) {
return when == msg->when;
}),
whens.end());
if (whens.empty()) {
mMapIdWhens.erase(msg->id);
}

LOGD("pop message id:%d, when:%lld", msg->id, msg->when);
return msg;
}
} while (0);
}
}

处理定时器到期消息

mTimerTickThread从mTimerTickQueue中取出到期的定时器消息后,再插入mCallbackQueue中,供mTimerCallbackThread线程调用回调函数完成定时器超时回调通知。

如果是循环定时器,则将定时消息的到期时间when加上超时时间timeout后重新插入mTimerTickQueue中,继续进行对应消息的流转。

do {
auto message = mTimerTickQueue->next();
if (!message) {
continue;
}
if (!message->callback) {
// No callback is a magic identifier for the quit message.
break;
}
do {
std::unique_lock ul(mMutexLock);
if (!message->valid) {
break;
}
if (PERIODIC_TIMER == message->type) {
(void)mTimerTickQueue->enqueueMessage(message,
message->when + message->timeout);
}

(void)mCallbackQueue->push_back(message);
ul.unlock();

mCond.notify_one();
std::this_thread::yield();
} while (0);
} while (mMainThreadAlive);

回调定时器回调函数

mTimerCallbackThread线程从mCallbackQueue中取出消息并调用回调函数完成定时器超时回调通知。

TimerMessageRefPtr message = nullptr;
do {
std::unique_lock ul(mMutexLock);
mCond.wait(ul, [this]() { return !mCallbackQueue->empty(); });

message = mCallbackQueue->front();
mCallbackQueue->pop_front();
if (!message) {
continue;
}
if (!message->callback) {
// No callback is a magic identifier for the quit message.
break;
}
if (!message->valid) {
continue;
}

// handler dispatch message.
LOGV("callback message id:%d, when:%lld", message->id, message->when);
message->callback();
ul.unlock();

std::this_thread::yield();
} while (mMainThreadAlive);

使用步骤举例

1.create timer manager instance

auto timerMgr = mdtimer::TimerManager::getInstance();

2.create timer instance

auto timer1 = timerMgr->create(50, std::bind(timeoutCallback, "once timer1, 50ms"));
auto timer2 = timerMgr->create(100, std::bind(timeoutCallback, "periodic timer2, 100ms"),
mdtimer::PERIODIC_TIMER);

3.start timer

(void)timer1->start();
(void)timer2->start();

4.stop timer

timer1->stop();
timer2->stop();

参考代码

定时器实现

/*
* Copyright (C) 2023 . All rights reserved.
*
* File name : MDTimer.hpp
* Author : longbin
* Created date: 2020-05-07 21:54:42
* Description : message driven timer
*
*/
#ifndef __MDTIMER_HPP__
#define __MDTIMER_HPP__

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

#ifdef LOG_TAG
# undef LOG_TAG
#endif // LOG_TAG
#define LOG_TAG "MDTimer"
#include "logging.hpp"

// usage:
// 1. create timer manager instance;
// auto timerMgr = mdtimer::TimerManager::getInstance();
// 2. create timer instance;
// auto timer1 = timerMgr -> create(50, std::bind(timeoutCallback, "once timer1, 50ms"));
// auto timer2 = timerMgr -> create(100, std::bind(timeoutCallback, "periodic timer2, 100ms"),
// mdtimer::PERIODIC_TIMER);
// 3. start timer;
// (void)timer1->start();
// (void)timer2->start();
// 4. stop timer;
// timer1->stop();
// timer2->stop();

namespace mdtimer
{

using TimerType = enum TimerType { ONCE_TIMER = 0, PERIODIC_TIMER = 1 };

class ITimer
{
public:
virtual ~ITimer() = default;

virtual bool start(void) = 0;
virtual void stop(void) = 0;
}; // class ITimer

class TimerManager : public std::enable_shared_from_this
{
private:
using TimerCallback = std::function;
class TimerMessage;
using TimerMessageRefPtr = std::shared_ptr;
using TimerMessageRefPtrList = std::deque;
using TimerManagerRefPtr = std::shared_ptr;

struct TimerMessage {
const int id; // time id.
const long long timeout; // time out value.
const TimerCallback callback; // timeout callback function.
const TimerType type; // 0:once, 1:periodic.
long long when; // time out occure time.
bool valid; // set true when timeout and pop from message queue.

TimerMessage()
: id(0), timeout(0), callback(nullptr), type(ONCE_TIMER), when(0), valid(false)
{}

TimerMessage(const int &id, const long long &timeout, const TimerCallback &callback,
const TimerType &type = ONCE_TIMER)
: id(id), timeout(timeout), callback(callback), type(type), when(0), valid(false)
{}
};

class TimerMessageQueue
{
private:
constexpr static bool mShowMessages = false;

TimerMessageRefPtrList mMessages{};
std::map> mMapIdWhens;
mutable std::mutex mMuxLock;
std::condition_variable mCond;

private:
TimerMessageQueue(const TimerMessageQueue &) = delete;
TimerMessageQueue &operator=(const TimerMessageQueue &) = delete;

inline void showMessages()
{
std::string queue{};
std::for_each(mMessages.begin(), mMessages.end(),
[&queue](const TimerMessageRefPtr &m) {
queue += std::to_string(m->id) + ":" + std::to_string(m->when) + " ";
});
LOGD("show messages (size:%zu) %s", mMessages.size(), queue.c_str());
}

inline void waitForItems(void)
{
std::unique_lock ul(mMuxLock);
mCond.wait(ul, [this]() { return !mMessages.empty(); });
if (0 == mMessages.front()->when) {
return;
}

long long waitingTimeMicros = 0;
while (!mMessages.empty()
&& (waitingTimeMicros = mMessages.front()->when - steadyTimeMicros()) > 0) {
// next message is not ready, set a timeout to wake up when it is ready.
mCond.wait_for(ul, std::chrono::microseconds(waitingTimeMicros));
}
}

public:
TimerMessageQueue() = default;
virtual ~TimerMessageQueue() = default;

TimerMessageRefPtr next(void)
{
while (true) {
waitForItems();
do {
std::lock_guard lg(mMuxLock); // minimise the lock scope.
if (!mMessages.empty()
&& (steadyTimeMicros() >= mMessages.front()->when)) { // time is up.
TimerMessageRefPtr msg = std::move(mMessages.front());
mMessages.pop_front();
msg->valid = true;

// remove message by id and when from map.
auto &whens = mMapIdWhens[msg->id];
whens.erase(std::remove_if(whens.begin(), whens.end(),
[&msg](const long long &when) {
return when == msg->when;
}),
whens.end());
if (whens.empty()) {
mMapIdWhens.erase(msg->id);
}

LOGD("pop message id:%d, when:%lld", msg->id, msg->when);
return msg;
}
} while (0);
}
}

bool enqueueMessage(const TimerMessageRefPtr &message, const long long &when)
{
do {
std::lock_guard lg(mMuxLock);
mMapIdWhens[message->id].push_back(when);
LOGD("add message id:%d, when:%lld", message->id, when);
message->when = when;
mMessages.insert(
std::upper_bound(mMessages.begin(), mMessages.end(), when,
[](const long long &when, const TimerMessageRefPtr &m) {
return (when < m->when);
}),
message);

if (mShowMessages) {
showMessages();
}
} while (0);

mCond.notify_one();
std::this_thread::yield();
return true;
}

void removeMessages(const int &id)
{
std::lock_guard lg(mMuxLock);
auto it = mMapIdWhens.find(id);
if (it == mMapIdWhens.end()) {
return;
}
for (auto const &when : it->second) {
LOGD("del message id:%d, when:%lld", id, when);
mMessages.erase(
std::remove_if(
std::lower_bound(mMessages.begin(), mMessages.end(), when,
[](const TimerMessageRefPtr &m, const long long &when) {
return (m->when < when);
}),
std::upper_bound(mMessages.begin(), mMessages.end(), when,
[](const long long &when, const TimerMessageRefPtr &m) {
return (when < m->when);
}),
[&id](const TimerMessageRefPtr &m) { return ((id == m->id)); }),
mMessages.end());
}
mMapIdWhens.erase(id);

if (mShowMessages) {
showMessages();
}
}

bool hasMessages(const int &id) const
{
std::lock_guard lg(mMuxLock);
bool ret = (mMapIdWhens.end() != mMapIdWhens.find(id));
LOGV("has message id:%d %s", id, ret ? "yes" : "no");
return ret;
// return mMessages.end()
// != std::find_if(mMessages.begin(), mMessages.end(),
// [&id](const TimerMessageRefPtr &m) { return ((id == m->id));
// });
}
}; // class TimerMessageQueue

class TimerImpl : public ITimer
{
friend class TimerManager; // to access its private start/stop
private:
TimerManagerRefPtr mTimerManager = nullptr;
TimerMessageRefPtr mTimerMessage = nullptr;

public:
explicit TimerImpl(const TimerManagerRefPtr &manager, const int &id,
const long long &timeoutMillis, const TimerCallback &callback,
const TimerType &type)
{
LOGI("create timer id:%d, timeout:%lldms, type:%d", id, timeoutMillis, type);
mTimerManager = manager;
mTimerMessage =
std::make_shared(id, timeoutMillis * 1000, callback, type);
}

virtual ~TimerImpl()
{
LOGI("destroy timer id:%d", mTimerMessage->id);
this->stop(); // if destroy timer manager before timer the stop will be blocked.
}

virtual bool start(void) override
{
mTimerMessage->when = mTimerMessage->timeout + steadyTimeMicros();
return mTimerManager ? mTimerManager->start(mTimerMessage) : false;
}

virtual void stop(void) override
{
if (mTimerManager) {
mTimerManager->stop(mTimerMessage);
}
}
}; // class TimerImpl

public:
virtual ~TimerManager()
{
LOGD("~TimerManager");
mMainThreadAlive = false;

(void)mCallbackQueue->push_back(std::make_shared());
mCond.notify_all();

(void)mTimerTickQueue->enqueueMessage(std::make_shared(), 0);
(void)mTimerTickQueue->enqueueMessage(std::make_shared(), -1);

if (mTimerTickThread.joinable()) {
mTimerTickThread.join();
}
if (mTimerCallbackThread.joinable()) {
mTimerCallbackThread.join();
}
}

static std::shared_ptr getInstance(void)
{
static std::shared_ptr instance =
std::shared_ptr(new TimerManager());
return instance;
}

std::shared_ptr create(const long long &timeoutMillis, const TimerCallback &callback,
const TimerType &type = ONCE_TIMER)
{
int id = mTimerId.fetch_add(1);
return std::shared_ptr(
new TimerImpl(shared_from_this(), id, timeoutMillis, callback, type));
}

static long long steadyTimeMicros(void)
{
auto now = std::chrono::time_point_cast(
std::chrono::steady_clock::now());
std::chrono::microseconds span =
std::chrono::duration_cast(now.time_since_epoch());
return span.count();
}

private:
TimerManager(const TimerManager &) = delete;
TimerManager &operator=(const TimerManager &) = delete;

TimerManager() : mMainThreadAlive(true)
{
mTimerTickThread = std::thread([this]() {
do {
auto message = mTimerTickQueue->next();
if (!message) {
continue;
}
if (!message->callback) {
// No callback is a magic identifier for the quit message.
break;
}
do {
std::unique_lock ul(mMutexLock);
if (!message->valid) {
break;
}
if (PERIODIC_TIMER == message->type) {
(void)mTimerTickQueue->enqueueMessage(message,
message->when + message->timeout);
}

(void)mCallbackQueue->push_back(message);
ul.unlock();

mCond.notify_one();
std::this_thread::yield();
} while (0);
} while (mMainThreadAlive);

LOGI("TimerTickThread exit.");
});

mTimerCallbackThread = std::thread([this]() {
TimerMessageRefPtr message = nullptr;
do {
std::unique_lock ul(mMutexLock);
mCond.wait(ul, [this]() { return !mCallbackQueue->empty(); });

message = mCallbackQueue->front();
mCallbackQueue->pop_front();
if (!message) {
continue;
}
if (!message->callback) {
// No callback is a magic identifier for the quit message.
break;
}
if (!message->valid) {
continue;
}

// handler dispatch message.
LOGV("callback message id:%d, when:%lld", message->id, message->when);
message->callback();
ul.unlock();

std::this_thread::yield();
} while (mMainThreadAlive);

LOGI("TimerCallbackThread exit.");
});
}

inline bool start(const TimerMessageRefPtr &message)
{
std::lock_guard lg(mMutexLock);
LOGI("start timer id:%d, timeout:%lldms", message->id, message->timeout / 1000);

// stop the exist timer then start.
if (mTimerTickQueue->hasMessages(message->id)) {
mTimerTickQueue->removeMessages(message->id);
}
mCallbackQueue->erase(std::remove_if(mCallbackQueue->begin(), mCallbackQueue->end(),
[&message](const TimerMessageRefPtr &m) {
return ((message->id == m->id));
}),
mCallbackQueue->end());
message->valid = false;

return mTimerTickQueue->enqueueMessage(message, message->when);
}

inline void stop(const TimerMessageRefPtr &message)
{
std::lock_guard lg(mMutexLock);
LOGI("stop timer id:%d", message->id);

if (mTimerTickQueue->hasMessages(message->id)) {
mTimerTickQueue->removeMessages(message->id);
}
mCallbackQueue->erase(std::remove_if(mCallbackQueue->begin(), mCallbackQueue->end(),
[&message](const TimerMessageRefPtr &m) {
return ((message->id == m->id));
}),
mCallbackQueue->end());
message->valid = false;
}

private:
std::atomic mTimerId{1};
std::shared_ptr mTimerTickQueue = std::make_shared();
std::shared_ptr> mCallbackQueue =
std::make_shared>();
std::atomic mMainThreadAlive{true};
std::thread mTimerTickThread;
std::thread mTimerCallbackThread;
mutable std::mutex mMutexLock;
std::condition_variable mCond;
}; // class TimerManager

}; // namespace mdtimer
#endif //__MDTIMER_HPP__,>()>

定时器使用例子

/*****************************************
* Copyright (C) 2020 * Ltd. All rights reserved.
* File name : mdtimertest.cpp
* Created date: 2020-05-07 00:35:00
*******************************************/

#include
#include
#include

#include
#include
// #include "callstack.h"

#include "MDTimer.hpp"

#ifdef LOG_TAG
# undef LOG_TAG
#endif // LOG_TAG
#define LOG_TAG "MDTimerTest"
#include "logging.hpp"

static void timeoutCallback(const std::string &info)
{
LOGI("timeoutCallback: %s", info.c_str());
}

void signal_SEGV_handler(int signo)
{
LOGE("caught signal: %d", signo);
// callstack_dump("CALLSTACK");
/* reset signal handle to default */
(void)signal(signo, SIG_DFL);
/* will receive SIGSEGV again and exit app */
}

int main()
{
(void)signal(SIGSEGV, signal_SEGV_handler);

auto timerMgr = mdtimer::TimerManager::getInstance();
if (timerMgr == nullptr) {
LOGE("ERROR: create timer failed.");
return -1;
}

// std::this_thread::sleep_for(std::chrono::seconds(3));
auto timer1 = timerMgr->create(50, std::bind(timeoutCallback, "once timer1, 50ms"));
(void)timer1->start();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
timer1->stop();

//周期性执行定时任务
auto timer2 = timerMgr->create(100, std::bind(timeoutCallback, "periodic timer2, 100ms"),
mdtimer::PERIODIC_TIMER);
(void)timer2->start();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
timer2->stop();

//周期性执行定时任务
auto timer3 = timerMgr->create(1000, std::bind(timeoutCallback, "periodic timer3, 1000ms"),
mdtimer::PERIODIC_TIMER);
(void)timer3->start();
std::this_thread::sleep_for(std::chrono::milliseconds(5000));

(void)timer1->start();
(void)timer2->start();
(void)timer3->start();
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
timer1->stop();
timer2->stop();
timer3->stop();

#if 1
auto timer4 = timerMgr->create(20, std::bind(timeoutCallback, "periodic timer4, 20ms"),
mdtimer::PERIODIC_TIMER);
(void)timer4->start();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
timer4->stop();
#endif
#if 0
auto timer5 = timerMgr->create(10, std::bind(timeoutCallback, "periodic timer5, 10ms"),
mdtimer::PERIODIC_TIMER);
for (auto i = 0; i < 2000; i++) {
(void)timer5->start();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
timer5->stop();
// std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
#endif

LOGI("the end.");
return 0;
}

运行log

2023-06-12 14:10:13.374461 13360 13360 I MDTimer:191 create TimerImpl id:1, timeout:50, type:0
2023-06-12 14:10:13.374531 13360 13360 I MDTimer:329 start id:1, timeout:50ms
2023-06-12 14:10:13.425528 13360 13362 I MDTimerTest:25 timeoutCallback: timer1: once, 50ms
2023-06-12 14:10:13.475776 13360 13360 I MDTimer:344 stop id:1
2023-06-12 14:10:13.475813 13360 13360 I MDTimer:191 create TimerImpl id:2, timeout:100, type:1
2023-06-12 14:10:13.475817 13360 13360 I MDTimer:329 start id:2, timeout:100ms
2023-06-12 14:10:13.577174 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:13.687436 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:13.778635 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:13.876929 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:13.976795 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:14.076345 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:14.177249 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:14.276597 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:14.376828 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:14.476367 13360 13360 I MDTimer:344 stop id:2
2023-06-12 14:10:14.476445 13360 13360 I MDTimer:191 create TimerImpl id:3, timeout:1000, type:1
2023-06-12 14:10:14.476460 13360 13360 I MDTimer:329 start id:3, timeout:1000ms
2023-06-12 14:10:15.477362 13360 13362 I MDTimerTest:25 timeoutCallback: timer3: periodic, 1000ms
2023-06-12 14:10:16.477212 13360 13362 I MDTimerTest:25 timeoutCallback: timer3: periodic, 1000ms
2023-06-12 14:10:17.477276 13360 13362 I MDTimerTest:25 timeoutCallback: timer3: periodic, 1000ms
2023-06-12 14:10:18.477688 13360 13362 I MDTimerTest:25 timeoutCallback: timer3: periodic, 1000ms
2023-06-12 14:10:19.476631 13360 13362 I MDTimerTest:25 timeoutCallback: timer3: periodic, 1000ms
2023-06-12 14:10:19.476740 13360 13360 I MDTimer:329 start id:1, timeout:50ms
2023-06-12 14:10:19.476775 13360 13360 I MDTimer:329 start id:2, timeout:100ms
2023-06-12 14:10:19.476784 13360 13360 I MDTimer:329 start id:3, timeout:1000ms
2023-06-12 14:10:19.527071 13360 13362 I MDTimerTest:25 timeoutCallback: timer1: once, 50ms
2023-06-12 14:10:19.576829 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:19.676966 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:19.777616 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:19.877071 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:19.978404 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:20.076912 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:20.177797 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:20.277207 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:20.377493 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:20.477006 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:20.477045 13360 13362 I MDTimerTest:25 timeoutCallback: timer3: periodic, 1000ms
2023-06-12 14:10:20.577124 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:20.677249 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:20.777554 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:20.878031 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:20.977304 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:21.076999 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:21.177763 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:21.277001 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:21.377242 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:21.477678 13360 13362 I MDTimerTest:25 timeoutCallback: timer2: periodic, 100ms
2023-06-12 14:10:21.477737 13360 13362 I MDTimerTest:25 timeoutCallback: timer3: periodic, 1000ms
2023-06-12 14:10:21.479624 13360 13360 I MDTimer:344 stop id:1
2023-06-12 14:10:21.479692 13360 13360 I MDTimer:344 stop id:2
2023-06-12 14:10:21.479707 13360 13360 I MDTimer:344 stop id:3
2023-06-12 14:10:21.479718 13360 13360 I MDTimer:191 create TimerImpl id:4, timeout:20, type:1
2023-06-12 14:10:21.479730 13360 13360 I MDTimer:329 start id:4, timeout:20ms
2023-06-12 14:10:21.499973 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.520535 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.540938 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.560465 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.584846 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.600391 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.619945 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.640485 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.661126 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.680551 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.700040 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.720451 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.741117 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.761350 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.780723 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.803386 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.820695 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.840791 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.860119 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.880511 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.900001 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.920576 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.941140 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.960555 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:21.980128 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.000512 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.019996 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.040414 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.060041 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.080564 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.099851 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.122287 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.140901 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.160394 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.179968 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.200225 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.220663 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.239965 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.260511 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.280020 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.305578 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.320103 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.340671 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.360015 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.380570 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.401000 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.420479 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.439866 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.460528 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.479953 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.500648 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.520394 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.540747 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.561312 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.580095 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.600382 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.620899 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.640418 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.659902 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.680163 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.703046 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.720542 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.740724 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.760168 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.780537 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.800054 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.820631 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.840785 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.860125 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.881097 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.900537 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.920620 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.941611 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.960467 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.979897 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:22.999982 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.020105 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.040916 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.060492 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.079993 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.100434 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.120644 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.140971 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.160481 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.181060 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.201456 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.222556 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.239880 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.260501 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.280484 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.299980 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.321099 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.340601 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.360090 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.380639 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.400425 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.422625 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.440473 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.460980 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.480272 13360 13362 I MDTimerTest:25 timeoutCallback: timer4: periodic, 20ms
2023-06-12 14:10:23.481266 13360 13360 I MDTimer:344 stop id:4
2023-06-12 14:10:23.481313 13360 13360 I MDTimerTest:88 the end.
2023-06-12 14:10:23.481323 13360 13360 I MDTimer:203 destroy TimerImpl id:4
2023-06-12 14:10:23.481329 13360 13360 I MDTimer:344 stop id:4
2023-06-12 14:10:23.481336 13360 13360 I MDTimer:203 destroy TimerImpl id:3
2023-06-12 14:10:23.481341 13360 13360 I MDTimer:344 stop id:3
2023-06-12 14:10:23.481348 13360 13360 I MDTimer:203 destroy TimerImpl id:2
2023-06-12 14:10:23.481353 13360 13360 I MDTimer:344 stop id:2
2023-06-12 14:10:23.481360 13360 13360 I MDTimer:203 destroy TimerImpl id:1
2023-06-12 14:10:23.481365 13360 13360 I MDTimer:344 stop id:1
2023-06-12 14:10:23.481371 13360 13360 I MDTimer:291 ~TimerManager.
2023-06-12 14:10:23.481467 13360 13361 I MDTimer:256 TimerTickThread exit.
2023-06-12 14:10:23.481629 13360 13362 I MDTimer:285 TimerCallbackThread exit.

后续思考

  1. 本定时器设计简洁高效,应用方便,满足绝大多数场景的使用;
  2. 当需要创建或管理大量定时器时,由于定时器start时插入消息时间复杂度为O(log2N),但stop时直接删除消息时间复杂度为O(N),因此引入了辅助的map用于解决该问题,使时间复杂度变为log2N;也可以使用时间轮定时器来优化,但处理逻辑会比较复杂。
打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分