boost asio 定时器 deadline_timer cancel

deadline_timer  cancel 功能还是挺方便的,举个例子,我们可以将它应用在网络收包中,用来等待数据包是否超时,实现超时重传的功能;以前在使用winpcap做帧数据传输时,用到这样的场景,因为考虑网络丢包的情况,需要对帧进行重传,在千兆网的协议中,有开始包,中间数据包,和结束包;收到一帧的第一个包后,启动定时器,当我们丢了结束包时,因为我们用结束包做一帧的结束标记,这是只能等到定时器超时,然后在重传该帧;在定时器超时的函数中实现重传功能;但是一般情况下不丢包,这是收到结束包后,我们需要取消定时器;

#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <iostream>
using namespace boost::asio;
using namespace std;

// timer handler 例子     
void timer_handler(boost::asio::deadline_timer* timer , const boost::system::error_code& err)    
{    
	if (err)    
	{    
		std::cout << "Timer cancel" << std::endl;    
	}    
	
	cout<< "hello Timer"<<endl;
}    

// timer 例子     
void timer_enable(boost::asio::deadline_timer* timer, size_t seconds_from_now)    
{    
	assert(timer);    
	timer->expires_from_now(boost::posix_time::seconds(seconds_from_now));    
	timer->async_wait(boost::bind(timer_handler, timer, boost::asio::placeholders::error));    
}   


int _tmain(int argc, _TCHAR* argv[])
{
	io_service ios;
	deadline_timer t(ios);

	timer_enable(&t,5);
	boost::asio::deadline_timer timer2(ios, boost::posix_time::seconds(2));
	timer2.wait();
	
	t.cancel();
	ios.run();

	return 0;
}

 

如果需要实现MFC 的Ontimer功能的话,只要在timer_handler函数 定时器时间到时,在次启动定时器就ok了。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值