ACE定时器

每一秒钟打印一行

http://www.tuicool.com/articles/Zb263e

计时器的打开和关闭封装

http://andylin02.iteye.com/blog/440572


自己写的简单计时器:程序开始之后2秒钟之后执行第一次到时触发的动作,以后每隔一秒钟都会执行相同的动作;当执行总次数到达3次之后就终止计时,整个程序退出,并停止事件监听,释放资源

#include <iostream>
#include "ace/Log_Msg.h"
#include "ace/Event_Handler.h"
#include "ace/Reactor.h"
#include "ace/Thread_Manager.h"

bool stop_event_loop = false;//是否需要终止计时器服务

class My_Timer_Handler : public ACE_Event_Handler
{
public:
    My_Timer_Handler(const int delay,const int interval);
    ~My_Timer_Handler();
    int handle_timeout(const ACE_Time_Value& , const void *act /* = 0 */);//计时器到期后执行的回调函数
private:
    int n_;//循环计时的次数
    long time_handle_;//在计时器队列中的ID
};

My_Timer_Handler::My_Timer_Handler(const int delay,const int interval):n_(0)
{
    std::cout<<"My_Timer_Handler()"<<std::endl;
    this->reactor(ACE_Reactor::instance());
    this->time_handle_ = this->reactor()->schedule_timer(this,//在这里注册定时器
        0,
        ACE_Time_Value(delay),//程序一开始延迟delay秒开始首次执行到期函数
        ACE_Time_Value(interval));//循环计时,每隔interval秒重复执行
}

My_Timer_Handler::~My_Timer_Handler()
{
    std::cout<<"~My_Timer_Handler()"<<std::endl;
}


int My_Timer_Handler::handle_timeout(const ACE_Time_Value& , const void *act /* = 0 */)
{
    if (++this->n_>3)
    {
        ACE_Reactor::instance()->cancel_timer(this->time_handle_);
        stop_event_loop = true;
        std::cout<<"cancle_timer"<<std::endl;
    }
    else
    {
        std::cout<<"my timer handler handled timeout"<<std::endl;
    }

    return 0;
}

int main(int argc, char* argv[])
{
    
    My_Timer_Handler my_handle(2,1);

    while (true)
    {
        if (stop_event_loop)
        {
            std::cout<<"stop handle time"<<std::endl;
            break;
        }
        ACE_Reactor::instance()->handle_events();
    }

    return 0;
}


 

运行结果如下:

My_Timer_Handler()
my timer handler handled timeout
my timer handler handled timeout
my timer handler handled timeout
cancle_timer
stop handle time
~My_Timer_Handler()
请按任意键继续. . .


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

C++程序员Carea

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

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

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

打赏作者

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

抵扣说明:

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

余额充值