Skip to content

1 上下文单例

cpp
/*********************************************************************************
 * @copyright Copyright (c) 2025  埃夫特智能装备股份有限公司
 *
 * @author Wu Wei (wuwei@efort.com.cn)
 * @version 0.1
 * @date 2025-05-07
 *
 * @file boost_io_context.h
 * @brief
 ********************************************************************************/

#pragma once
#include <boost/asio.hpp>
#include <thread>
namespace efortrl {
// BoostIOContext Singleton class
class BoostIOContext
{
private:
    BoostIOContext();  // Private constructor
    BoostIOContext(const BoostIOContext&) = delete;
    BoostIOContext(BoostIOContext&&) = delete;
    BoostIOContext& operator=(const BoostIOContext&) = delete;
    BoostIOContext& operator=(BoostIOContext&&) = delete;

    boost::asio::io_context _context;
    boost::asio::executor_work_guard<boost::asio::io_context::executor_type> _workGuard;
    std::thread _thread;

public:
    ~BoostIOContext();
    static BoostIOContext& instance();
    boost::asio::io_context& context();
};

}  // namespace efortrl
cpp
/*********************************************************************************
 * @copyright Copyright (c) 2025  埃夫特智能装备股份有限公司
 *
 * @author Wu Wei (wuwei@efort.com.cn)
 * @version 0.1
 * @date 2025-05-07
 *
 * @file boost_io_context.h
 * @brief
 ********************************************************************************/
#include "boost_io_context.h"
namespace efortrl {

BoostIOContext::BoostIOContext() : _workGuard{boost::asio::make_work_guard(_context)}
{
    _thread = std::thread([&]() { _context.run(); });
}
BoostIOContext::~BoostIOContext()
{
    _context.stop();
    if (_thread.joinable()) _thread.join();
}
BoostIOContext& BoostIOContext::instance()
{
    static BoostIOContext instance;
    return instance;
}
boost::asio::io_context& BoostIOContext::context() { return _context; }
}  // namespace efortrl

2 节流装置

cpp
/*********************************************************************************
 * @copyright Copyright (c) 2025  埃夫特智能装备股份有限公司
 *
 * @author Wu Wei (wuwei@efort.com.cn)
 * @version 0.1
 * @date 2025-05-07
 *
 * @file throttler.h
 * @brief
 ********************************************************************************/

#pragma once
#include <boost/asio.hpp>
#include <functional>
#include <iostream>
#include <mutex>
namespace efortrl {

class Throttler
{
public:
    typedef std::chrono::steady_clock Clock;
    typedef std::chrono::milliseconds Duration;
    typedef Clock::time_point TimePoint;

    Throttler(boost::asio::io_context& io, int intervalMs)
        : _timer(io), _interval(std::chrono::milliseconds(intervalMs)), _ready(true)
    {
    }

    ~Throttler() { _timer.cancel(); }

    template <typename F, typename... Args>
    void exectue(F&& f, Args&&... args)
    {
        // 获取当前时间
        auto now = Clock::now();
        // 计算剩余等待时间
        auto remaining = _interval - (now - _previous);

        // 取消之前的定时器(如果有)
        boost::system::error_code ec;
        _timer.cancel(ec);

        std::function<decltype(f(args...))()> func =
            std::bind(std::forward<F>(f), std::forward<Args>(args)...);

        // 如果不需要等待,立即执行函数
        if (remaining <= Duration::zero())
        {
            func();
            // 更新最后执行时间
            _previous = now;
        } else
        {
            // 需要等待,设置定时器延迟执行
            _timer.expires_after(remaining);
            // 异步等待定时器触发
            _timer.async_wait([this, func](const boost::system::error_code& ec) {
                // 定时器回调函数(在IO线程执行)
                if (!ec)
                {  // 只有定时器正常触发才执行 callback
                    func();
                    // 更新最后执行时间
                    _previous = Clock::now();
                }
            });
        }
    }

private:
    boost::asio::steady_timer _timer;
    Duration _interval;   // 节流时间间隔
    TimePoint _previous;  // 上次执行的时间点
    bool _ready;
};

}  // namespace efortrl

3 定时器

cpp
/*********************************************************************************
 * @copyright Copyright (c) 2025  埃夫特智能装备股份有限公司
 *
 * @author Wu Wei (wuwei@efort.com.cn)
 * @version 0.1
 * @date 2025-05-09
 *
 * @file boost_timer.h
 * @brief boost 定时器, 用于执行定时任务
 ********************************************************************************/

#pragma once
#include <boost/asio.hpp>
#include <functional>
#include <iostream>

namespace efortrl {

class BoostTimer
{
public:
    BoostTimer(boost::asio::io_context& io, int timeout, int repeatTimes)
        : _timer(io), _timeout(std::chrono::milliseconds(timeout)), _repeatTimes(repeatTimes)
    {
    }

    ~BoostTimer() { _timer.cancel(); }

    void start()
    {
        if (_repeatTimes == 0)
        {
            return;  // 如果重复次数为0,直接返回
        }

        // 启动定时器
        _timer.expires_after(_timeout);
        _timer.async_wait([this](const boost::system::error_code& ec) { onTimeout(ec); });
    }

    void onTimeout(const boost::system::error_code& ec)
    {
        if (!ec)
        {
            --_repeatTimes;

            // 如果重复次数不为0, 重置定时器
            if (_repeatTimes != 0)
            {
                _timer.expires_after(_timeout);
                _timer.async_wait([this](const boost::system::error_code& ec) { onTimeout(ec); });
            }

            if (_callback != nullptr) _callback();  // 执行回调
        }
    }

    template <typename F, typename... Args>
    void setTimeoutCallback(F&& f, Args&&... args)
    {
        // 要执行的操作
        std::function<decltype(f(args...))()> func =
            std::bind(std::forward<F>(f), std::forward<Args>(args)...);

        _callback = func;  // 设置回调
    }

private:
    boost::asio::steady_timer _timer;
    std::chrono::milliseconds _timeout;
    int _repeatTimes;
    std::function<void()> _callback;
};
}  // namespace efortrl

基于 VitePress 构建