实现一个定时器

首先,定时器是一个处理延时任务的模块。即组织大量定时任务,确保准确的执行某个任务。

1、定时器如何实现?

数据结构+检测机制,其中数据结构再增删改后保持有序。

因此我们需要的数据结构需要为红黑树、最小堆、时间轮等数据结构。

检测机制(优雅的等待) 建议使用epoll

定时器的设计

我们的定时器Timer是处理延时任务,因此我们需要拥有以下属性:

  • uint64_t m_ms   时间
  • std::chrono::time_point<std::chrono::system_clock> m_next  绝对超时时间(系统时间+m_ms)
  • m_cb   回调函数
  • bool m_recurring  是否为循环定时任务(一次性任务还是永久性,若次数有限个人感觉代替为可计数单位)

定时任务需要管理器来实现因此我们需要设计一个定时器调度中心TimerManager

  • std::shared_mutex m_mutex 读写锁

  • std::set<std::shared_ptr<Timer>, Timer::Comparator> m_times; 时间堆,set其实是红黑树数据结构

  • bool m_tickled = false;   //标识位,防止在一次事件循环 tick 内多次调用

  • std::chrono::time_point<std::chrono::system_clock> m_previousTime  获取当前时间

Timer类的设计

//构造函数
Timer::Timer(uint64_t ms, std::function<void()> cb,bool recurring,TimerManager *manager):m_ms(ms),m_cb(cb),m_manger(manager),m_recurring(recurring)
{
    auto now = std::chrono::system_clock::now();
    m_next = now + std::chrono::milliseconds(m_ms);
}

// 从时间堆中删除timer
bool Timer::cancel(){
    std::unique_lock<std::shared_mutex> write_lock(m_manger->m_mutex);
    //函数置空
    if(m_cb == nullptr) 
    {
        return false;
    }
    else
    {
        m_cb = nullptr;
    }
    //找出需要删除的timer
    auto it = m_manger->m_times.find(shared_from_this());
    if(it!=m_manger->m_times.end())
    {
        m_manger->m_times.erase(it);
    }
    return true;

}

   // 刷新timer
bool Timer::refresh(){
    std::unique_lock<std::shared_mutex> write_lock(m_manger->m_mutex);

    if(m_cb == nullptr){
        return false;
    }
    auto it = m_manger->m_times.find(shared_from_this());
    if(it==m_manger->m_times.end())
    {
        return false;
    }
    //先删除,再加入
    m_manger->m_times.erase(it);
    m_next = std::chrono::system_clock::now() + std::chrono::milliseconds(m_ms);
    m_manger->m_times.insert(shared_from_this());
    return true;
}

   // 重设timer的超时时间
bool Timer::reset(uint64_t ms, bool from_now){
    if(ms==m_ms && !from_now)
    {
        return true;
    }

    {
        std::unique_lock<std::shared_mutex> write_lock(m_manger->m_mutex);
    
        if(!m_cb) 
        {
            return false;
        }
        
        auto it = m_manger->m_times.find(shared_from_this());
        if(it==m_manger->m_times.end())
        {
            return false;
        }   
        m_manger->m_times.erase(it); 
    }
     // reinsert
    auto start = from_now ? std::chrono::system_clock::now() : m_next - std::chrono::milliseconds(m_ms);
    m_ms = ms;
    m_next = start + std::chrono::milliseconds(m_ms);
    m_manger->addTimer(shared_from_this());
    return true;
}

bool Timer::Comparator::operator()(const std::shared_ptr<Timer>& lhs, const std::shared_ptr<Timer>& rhs) const
{
    assert(lhs!=nullptr&&rhs!=nullptr);
    return lhs->m_next < rhs->m_next;
}

Comparator 通过比较 m_next(绝对超时时间点)来实现 升序排序

TimerManager类

TimerManager::TimerManager() 
{
    m_previousTime = std::chrono::system_clock::now();
}

TimerManager::~TimerManager() 
{
}

std::shared_ptr<Timer> TimerManager::addTimer(uint64_t ms, std::function<void()> cb,bool recurring){
    std::shared_ptr<Timer> timer(new Timer(ms, cb, recurring, this));
    addTimer(timer);
    return timer;

}
void TimerManager::addTimer(std::shared_ptr<Timer> timer){
    bool at_front = false;
    {
        std::unique_lock<std::shared_mutex> write_lock(m_mutex);
        auto it = m_times.insert(timer).first;
        at_front = (it == m_times.begin()) && !m_tickled;
        
        // only tickle once till one thread wakes up and runs getNextTime()
        if(at_front)
        {
            m_tickled = true;
        }
    }
   
    if(at_front)
    {
        // wake up 
        onTimerInsertedAtFront();
    }
}

// 如果条件存在 -> 执行cb()
static void OnTimer(std::weak_ptr<void> weak_cond, std::function<void()> cb)
{
    std::shared_ptr<void> tmp = weak_cond.lock();
    if(tmp)
    {
        cb();
    }
}

std::shared_ptr<Timer> TimerManager::addConditionTimer(uint64_t ms, std::function<void()> cb, std::weak_ptr<void> weak_cond, bool recurring) 
{
    return addTimer(ms, std::bind(&OnTimer, weak_cond, cb), recurring);
}
//拿到最近超时的时间
uint64_t TimerManager::getNextTimer()
{
    std::shared_lock<std::shared_mutex> read_lock(m_mutex);
    
    // reset m_tickled
    m_tickled = false;
    
    if (m_times.empty())
    {
        // 返回最大值
        return ~0ull;
    }

    auto now = std::chrono::system_clock::now();
    auto time = (*m_times.begin())->m_next;

    if(now>=time)
    {
        // 已经有timer超时
        return 0;
    }
    else
    {   // 距离下一次定时器到期还剩多少时间” 算出来
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(time - now);
        return static_cast<uint64_t>(duration.count());            
    }  
}
// 取出所有超时定时器的回调函数
void TimerManager::listExpiredCb(std::vector<std::function<void()>>& cbs)
{
    auto now = std::chrono::system_clock::now();

    std::unique_lock<std::shared_mutex> write_lock(m_mutex); 

    bool rollover = detectClockRollover();
    
    // 回退 -> 清理所有timer || 超时 -> 清理超时timer
    while (!m_times.empty() && rollover || !m_times.empty() && (*m_times.begin())->m_next <= now)
    {
        std::shared_ptr<Timer> temp = *m_times.begin();
        m_times.erase(m_times.begin());
        
        cbs.push_back(temp->m_cb); 
        // 是否是循环事件
        if (temp->m_recurring)
        {
            // 重新加入时间堆
            temp->m_next = now + std::chrono::milliseconds(temp->m_ms);
            m_times.insert(temp);
        }
        else
        {
            // 清理cb
            temp->m_cb = nullptr;
        }
    }
}
bool TimerManager::hasTimer() 
{
    std::shared_lock<std::shared_mutex> read_lock(m_mutex);
    return !m_times.empty();
}

bool TimerManager::detectClockRollover() 
{
    bool rollover = false;
    auto now = std::chrono::system_clock::now();
    if(now < (m_previousTime - std::chrono::milliseconds(60 * 60 * 1000))) 
    {
        rollover = true;
    }
    m_previousTime = now;
    return rollover;
}

简单实现了一个自动执行的定时任务,使用timerfd实现更为简便。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值