c++ Implementing Timed Callback function

前端 未结 4 646
别跟我提以往
别跟我提以往 2020-12-04 22:18

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:

callfu         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 23:22

    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 
    #include 
    #include 
    #include 
    #include 
    
    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
    

提交回复
热议问题