c++实现定时回调函数

标签 c++ callback function-pointers timing

我想在 C++ 中实现一些系统,以便我可以调用一个函数并要求在 X 毫秒内调用另一个函数。像这样的:

callfunctiontimed(25, funcName);

25 是调用函数之前的毫秒数。

我想知道这是否需要多线程,然后使用一些延迟功能?除了使用函数指针之外,这样的功能如何工作?

最佳答案

对于可移植解决方案,您可以使用 boost::asio。下面是我前段时间写的一个demo。 你可以改变

t.expires_from_now(boost::posix_time::seconds(1));

为了适合你需要在 200 毫秒后调用函数。

t.expires_from_now(boost::posix_time::milliseconds(200)); 

下面是一个完整的工作示例。它在重复调用,但我认为只需稍微更改一下就可以轻松调用一次。

#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

using namespace boost::asio;
using namespace std;

class Deadline 
{
public:
    Deadline(deadline_timer &timer) : t(timer) {
        wait();
    }

    void timeout(const boost::system::error_code &e) {
        if (e)
            return;
        cout << "tick" << endl;
        wait();
    }

    void cancel() {
        t.cancel();
    }


private:
    void wait() {
        t.expires_from_now(boost::posix_time::seconds(1)); //repeat rate here
        t.async_wait(boost::bind(&Deadline::timeout, this, boost::asio::placeholders::error));
    }

    deadline_timer &t;
};


class CancelDeadline {
public:
    CancelDeadline(Deadline &d) :dl(d) { }
    void operator()() {
        string cancel;
        cin >> cancel;
        dl.cancel();
        return;
    }
private:
    Deadline &dl;
};



int main()
{
    io_service io;
    deadline_timer t(io);
    Deadline d(t);
    CancelDeadline cd(d);
    boost::thread thr1(cd);
    io.run();
    return 0;
}



//result:
//it keeps printing tick every second until you enter cancel and enter in the console
tick
tick
tick

关于c++实现定时回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12904098/

相关文章:

c++ - 数组的卷积

c++ - 拥有 `ConstBufferSequence`的boost::asio数据

multithreading - 如何在从非 Qt 多线程库调用的 QObject 派生类中实现回调函数?

c++ - 使用方法指针启动线程

c++ - 函数指针的比较是否合法

c# - 将结构从 C++ 传递到 CLI

c++ - 类实例成员初始化

c++ - 如果基类和派生类都需要使用相同的函数,回调函数应该去哪里?

c# - 将 C 回调函数封装在 C# 函数中

C++ 指向成员函数的指针作为模板默认参数