c ++实现定时回调函数 [英] c++ Implementing Timed Callback function
问题描述
我想在c ++中实现一些系统,这样我可以调用一个函数,并要求另一个函数在X毫秒内调用。像这样:
I want to implement some system in c++ so that I can call a function and ask for another function to be called in X milliseconds. Something like this:
callfunctiontimed(25, funcName);
25是函数调用前的毫秒数。
25 being the amount of milliseconds before the function should be called.
我想知道是否需要多线程,然后使用一些延迟功能?
I would like to know if multithreading is required for this and then use some delay function? Other than using function pointer how would a feature like this work?
推荐答案
对于一个可移植的解决方案,你可以使用boost :: asio 。下面是我写的一个演示。
您可以更改
For a portable solution, you can use boost::asio. Below is a demo I wrote a while ago. You can change
t.expires_from_now(boost::posix_time::seconds(1));
以满足您需要说在200年后调用函数调用。
to suit you need say make function call after 200 milliseonds.
t.expires_from_now(boost::posix_time::milliseconds(200));
下面是一个完整的工作示例。它反复呼叫,但我认为应该很容易只调用一次只需更改一点。
Below is a complete working example. It's calling repeatedly but I think it should be easy to call only once by just change a bit.
#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 ++实现定时回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!