c++ Implementing Timed Callback function

DavidColson picture DavidColson · Oct 15, 2012 · Viewed 41.9k times · Source

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 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?

Answer

Gob00st picture Gob00st · Oct 16, 2012

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));

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