用boost的asio+deadline_timer实现一个循环定时器

利用boost实现定时器 #include <iostream> #include <string> #include <boost/asio.hpp> #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/asio/steady_timer.hpp> #include <bo... 阅读详情

废话不多说, asio的原理请百度其它博文, 百度上好多deadline_timer的例子都是单次定时, 或者是封装的很长. 本文写的是一个超简单的例子来实现循环定时, 注意这个循环的周期是可变的, 可以每5秒固定周期执行, 也可以1秒/5秒/2秒变周期执行, 或者指定一个绝对时间来执行.

 

#include "stdafx.h"
#include <boost/asio.hpp>

using namespace std;
using namespace boost;
using namespace boost::posix_time;
using namespace boost::asio;

io_service io;
deadline_timer ti5s(io, seconds(5));

void timer_wait5s(const boost::system::error_code& err)
{
	cout << "time out: 5s" << endl;
	ti5s.expires_from_now(seconds(5));                 // 用法1.
	//ti5s.expires_at(ti5s.expires_at() + seconds(5)); // 用法2.
	ti5s.async_wait(timer_wait5s);

}


int _tmain(int argc, _TCHAR* argv[])
{
	ti5s.async_wait(timer_wait5s);
	io.run();

	return 0;
}

有一点要说明的:

- 代码中标的用法1: expires_from_now函数, 用于在当前时间之后的5秒再次执行异步, 这是个相对时间

- 代码中标的用法2: expires_at函数, 用于指定时间后再次执行异步, 这是个绝对时间, 在代码里的绝对时间是ti5s.expires_at(ti5s.expires_at() + seconds(5)); 也就是从现在开始后5秒这个绝对时间点

 

Boost.Asio异步网络编程调试与测试实战指南 异步编程是现代高性能网络应用的核心技术,它通过事件驱动和非阻塞I/O模型,在单线程或多线程中高效处理海量并发连接。其原理基于事件循环和回调机制,将I/O等待时间释放出来,从而大幅提升系统吞吐量。这项技术的核心价值在于能够构建高并发、低延迟的服务器和分布式系统。在C++生态中,Boost.Asio库是实现异步网络编程的工业级标准框架,广泛应用于游戏服务器、金融交易系统和物联网网关等场景。然而,异步编程的复杂性也带来了独特的调试挑战,例如事件循环的不可预测性、回调执行顺序的随机性以及资源生命周期的精细管理。针对 阅读详情

相关推荐

基于Boost.Asio的C++异步网络服务器开发实战指南

网络编程中的并发与I/O处理是构建高性能服务的关键挑战。传统同步阻塞模型存在资源消耗大、性能瓶颈明显的问题,而原生异步API如epoll和IOCP虽然高效但跨平台兼容性差。Boost.Asio库通过前摄器模式抽象了底层I/O复用机制,提供了统一的异步编程接口,使开发者能够编写高性能、可扩展的网络应用。其核心价值在于简化了异步操作的生命周期管理,通过io_context实现事件循环调度,结合智能指针管理连接会话,有效解决了C10K等高并发场景下的连接管理难题。在工程实践中,Boost.Asio广泛应用于游戏服

weixin_33816946的博客 1066

从游戏服务器到物联网网关:用Boost.Asio的deadline_timer构建跨平台定时任务系统

本文深入探讨了如何利用Boost.Asio的deadline_timer构建高性能跨平台定时任务系统,适用于游戏服务器和物联网网关等场景。通过分析传统定时方案的缺陷,展示了Boost.Asio在精度、跨平台兼容性和异步I/O集成方面的优势,并提供了实战技巧和高级应用模式,帮助开发者实现工业级定时服务。

weixin_27943395的博客 397

基于Boost.Asio的C++高性能异步网络服务架构设计与实践

异步I/O是现代高性能网络服务的核心技术,其核心原理在于将耗时的I/O操作交由系统内核异步处理,避免线程阻塞,从而在单线程或少量线程下支撑海量并发连接。这种技术价值在于极大提升了服务器的吞吐量和资源利用率,是实现高并发、低延迟网络应用的基础。在实际工程中,异步I/O框架如Boost.Asio,通过统一的Proactor模式抽象,将网络、文件等多种I/O操作纳入同一事件循环管理,简化了开发模型。其典型应用场景包括游戏服务器、实时通信系统、金融交易网关等对性能要求苛刻的领域。本文聚焦于利用Boost.Asio整

weixin_34033624的博客 394

【Boost】boost库中timer定时器

同步Timer asio中提供的timer名为deadline_timer,它提供了超时计时的功能。首先以一个最简单的同步Timer为例来演示如何使用它。     #include      #include      int main()     {         boost::asio::io_service io;         boost::asio:

liujiayu2的专栏 1万+

C++网络编程实战:Boost.Asio异步模型与套接字编程详解

网络编程是构建分布式系统和网络应用的核心技术,其核心在于高效处理多并发连接与I/O操作。传统阻塞式套接字编程在应对C10K等高并发场景时面临性能瓶颈,因此异步I/O与事件驱动模型成为现代高性能网络框架的基石。Boost.Asio作为C++领域广泛使用的跨平台网络库,通过封装epoll、IOCP等系统级异步机制,提供了统一的Proactor模式接口,实现了真正的非阻塞I/O。其技术价值在于允许单线程或线程池高效管理海量连接,极大提升了程序的吞吐量与资源利用率,广泛应用于游戏服务器、金融交易系统、实时通信等高性

weixin_30751947的博客 376

boost::asio::deadline_timer定时器详解

同步等待:阻塞当前线程直到指定时间点。异步等待:注册回调函数,在指定时间点被调用,不阻塞主线程。其底层实现依赖于操作系统的时间服务,可以在 Windows 上使用,在 Linux 上使用timerfd或其他机制。特性时间单位推荐程度老版本可用新项目推荐是否支持异步✅✅是否可重复使用✅✅。

h a 6 6 6 c k 为 你解决复杂难题! 323

boost:asio与定时器

头文件理论目标类basic_waitable_timer是定时器的真正实现,steady_timer、system_timer、high_resolution_timer是basic_waitable_timer的模板特化。

OceanStar的博客 1872

Excel炒股党必备:手把手教你用Power Query免费获取并刷新股票历史数据

本文详细介绍了如何利用Excel中的Power Query工具免费获取并自动刷新股票历史数据,特别适合Excel炒股党。从环境配置、数据源选择到实战操作,手把手教你建立智能数据管道,实现高效投资分析。通过参数化股票代码和定时刷新功能,大幅提升数据更新效率。

weixin_26767391的博客 654

(一)基于BOOST ASIO封装的定时器

(一)基于BOOST ASIO封装的定时器 代码 //20190831 xushuilong #pragma once #include <iostream> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> class Timer

小飞侠的博客 557

Arco Design Pro PC端商家后台框架 | Axure高保真原型库

摘要:本Axure原型设计方案基于字节跳动ArcoDesignPro规范,提供企业级后台快速搭建方案。包含动态表格、表单验证等核心组件,采用中继器驱动设计,支持响应式布局。方案覆盖80%后台常用交互,可节省60%原型制作时间,配套完整设计文档和组件库,实现原型到开发的高效衔接。特别适用于电商、SaaS等后台系统开发,支持权限管理、数据分析等场景,显著提升团队协作效率。

招风的黑耳优快云 3973

【Kingbase人大金仓】授权文件更换

本文介绍了金仓数据库授权文件更换的步骤:1.通过ksql或客户端工具查询数据库版本;2.在官网下载对应版本的license.bat文件;3.替换前先备份原授权文件(使用tar命令压缩),再用新文件覆盖原文件。注意事项包括:版本号需严格对应,授权文件通常位于安装目录下,可使用find命令查找具体位置。操作需谨慎,建议先备份原文件以便恢复。

qq_34463511的博客 3459

boost::asio::io_context的事件循环

简介 boost::asio::io_context看字面意思是io的上下文, 可以理解为, boost的任何io都会涉及到一个io_context, 同步io会隐式地启动一个io_context, 而异步io需要我们指定一个, 然后在合适的时机调用io_context::run()函数, 之后会进入io事件循环, 如果io完成会调用回调函数, 保证实现有关的功能. 根据官方文档, 在已经启动io...

Erick Lv的笔记 1万+

从零到一:TI AWR1843 Boost EVM与DCA1000 EVM的ADC数据采集实战指南

本文详细介绍了TI AWR1843 Boost EVM与DCA1000 EVM的ADC数据采集实战指南,涵盖硬件连接、软件配置、固件烧录、雷达参数设置及数据处理等关键步骤。通过MATLAB等工具,开发者可高效实现毫米波雷达数据采集,适用于自动驾驶、工业检测等领域。

weixin_29001327的博客 967

boost.asio: deadline_timer源码剖析

boost asio源码

Erice_s的博客 1477

基于 YOLOv26 的高速抛物识别系统:微小目标检测

本文提出了一种基于YOLOv26的高速抛物识别系统,专注于微小目标检测。系统采用多模块协同架构,包括视频预处理、YOLOv26检测、目标跟踪和抛物行为分析等模块。关键技术包括YOLOv26s模型检测、DeepSORT目标跟踪和边缘计算部署。通过构建包含多种抛物类型的专业数据集,并应用数据增强技术提升模型性能。系统实现了车辆检测、微小抛物目标识别、抛物轨迹分析和风险等级评估等功能,可实时检测高速公路上的抛物行为并触发告警,为交通管理提供智能化解决方案。

一键难忘的博客 632

SAP-ABAP:FI财务会计模块常用BAPI及核心用途实例说明

SAP FI模块的BAPI覆盖了从主数据管理、凭证过账到财务关账的全流程操作,是系统集成与自动化的重要工具。实际应用中需结合业务场景选择合适的BAPI,并严格遵循事务控制与校验规则。如需扩展功能,可通过BAdI或用户出口增强标准逻辑。

baidu_35680696的博客 1601

boost::asio名字空间中的deadline_time类:定时器

定时器是asio库中最简单的一个IO模型,提供等候时间终止的功能。 定时器功能的主要类是:deadline_timer类,类摘要如下使用定时器时的头文件:#include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace boost::asio;1. 同步定时器//同步定时器的用

yvhqbat的博客 1125

Unity实战篇 | 教你怎样将Unity的启动Logo 设置成 自己制作的 帧动画

上一篇文章我们讲了怎样在不购买专业版的情况下自定义Unity的启动Logo。 那本篇文章就来介绍一下,怎样在去除默认Logo的前提下制作自己的启动动画!

努力前行,总会成为自己心中的那道光 6万+

Boost.Asio C++ 网络编程之十一:deadline_timer使用说明

       deadline_timer和socket一样,都用io_service作为构造函数的参数。也即,在其上进行异步操作,都将导致和io_service所包含的iocp相关联。这同样意味着在析构 io_service之前,必须析构关联在这个io_service上的deadline_timer。一.构造函数在构造deadline_timer时指定时间。basic_deadline_time...

草上爬的博客 5197

开源3D激光SLAM算法的异同点、优劣势与适配场景总结

本文对比分析了主流开源3D激光SLAM方案的核心差异与适用场景。LOAM架构简洁但精度较低;LeGO-LOAM轻量化适合地面机器人;LIO-SAM采用因子图优化支持多传感器融合;LVI-SAM通过视觉-激光-惯性三重冗余提升鲁棒性;FAST-LIO系列基于滤波架构实现超高实时性。选型需权衡传感器配置(纯激光/激光+IMU/激光+视觉)、运动状态(高速/常规)、计算资源等因素:资源受限选LeGO-LOAM或Faster-LIO,高速运动选FAST-LIO系列,退化环境选LVI-SAM,全局一致性需求选LIO-

Studying…… 651

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

boos库中asio定时器使用示例

原文:http://www.voidcn.com/article/p-efmozrnt-bex.html 异步定时器 和 同步定时器,简单示例: #include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #inclu...

reason的博客 485

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

【Boost】boost库asio详解4——deadline_timer使用说明

deadline_timer和socket一样,都用io_service作为构造函数的参数。也即,在其上进行异步操作,都将导致和io_service所包含的iocp相关联。这同样意味着在析构 io_service之前,必须析构关联在这个io_service上的deadline_timer。 1. 构造函数 在构造deadline_timer时指定时间。 [cpp] view

yuzonghuan的专栏 565

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

boost::asio 定时器

转:http://blog.youkuaiyun.com/gubenpeiyuan/article/details/8013221 boost::asio 定时器 - boost中文文档 boost::asio - boost中文文档 所有的 asio 类都只要包含头文件:   "asio.hpp" 目录(?)[-] 例子1   使用一个同步的定时器例子2 使

P20914065的专栏 857

基于C++与Boost.Asio的BleuIO BLE设备扫描方案

蓝牙低功耗(BLE)技术作为物联网设备通信的核心协议,其工作原理基于低功耗射频与广播/扫描机制,在嵌入式与工业物联网场景中具有重要技术价值。针对Python等脚本语言在性能与底层控制上的局限,采用C++结合Boost.Asio异步I/O库,通过串口直接操作BleuIO蓝牙适配器,实现了对BLE设备扫描的高效、可控解决方案。该方案通过统一的AT命令接口进行设备交互,利用异步事件驱动模型处理串口通信与数据解析,支持设备去重、信号平滑及多适配器负载均衡等高级功能,适用于对稳定性、实时性要求严苛的工业数据采集与嵌入

weixin_34129696的博客 371

Boost asio

asio(asynchronous input and output) 表示异步输入输出,是基于操作系统提供的异步机制,异步数据处理表示触发后不需要等待完成,期间可以执行其他任务,而且不要求使用多线程和锁定,有效避免了条件竞争,死锁等。asio主要用于网络通信方面,支持TCP,UDP,ICMP等网络通信协议。asioasio主要分为同步和异步两种方式,同步表示同步等待,比如网络连接时,客户端发出请求

freehyan的博客 1879

简单的几个Boost定时器

  boost 的asio库里有几个定时的器,老的有 deadline_timer, 还有三个可配合 C++11 的 chrono 使用的 high_resolution_timer、steady_timer和 system_timer。   老的 deadline_timer我不太想用了,因为用起来没有后面三个好用。但是后面三个没有 C++ 11 也不好用。   ...

weixin_30642267的博客 302
上一篇: APAMA学习笔记(一) APAMA的安装与Hello world
下一篇: c#中调用dll时报无法加载模块的几种常见原因
蟾宫伐桂
博客等级 码龄26年 11粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值