boost.asio定時器dealine_timer,實現可以隨時控制啓動停止和設置時間。

dealine_timer類的成員函數
![這裏寫圖片描述](https://img-blog.csdn.net/20150317163110237)
定時器dealine_timer有兩種形式的構造函數,都要求有一個io_service對象,用於提交IO請求,第二個參數是定時器的終止時間,可以是posix_time的絕對時間點或者是自當前時間開始的一個時間長度。
一旦定時器對象創建,它就立即開始計時,可以使用成員函數wait()來同步等待定時器終止,或者使用async_wait()異步等待,當定時器終止是會調用handler函數。
如果創建定時器時不指定終止時間,那麼定時器不會工作,可以用成員函數expires_at()和expires_from_now()分別設置定時器終止絕對時間和相對時間,然後調用wait()和async_wait()等待。這兩個函數也可以用與獲得定時器的終止時間,只需要使用它們的無參重載形式。
定時器還有一個cancel()函數,它的功能是通知所有的異步操作取消,轉而等待定時器終止。
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>

class MyTimer
{

public:
    template<typename F>
    MyTimer(boost::asio::io_service& ios, F func, int interval, bool start = true) :
        m_func(func),
        m_interval(interval),
        m_timer(ios, boost::posix_time::millisec(interval)), 
        m_flag(start)
    {
        m_timer.async_wait(boost::bind(&MyTimer::call_func, this, boost::asio::placeholders::error));
    }
    void call_func(const boost::system::error_code&)
    {
        if (!m_flag)
        {
            return;
        }
        m_func();
        m_timer.expires_at(m_timer.expires_at() + boost::posix_time::millisec(m_interval));
        m_timer.async_wait(boost::bind(&MyTimer::call_func, this, boost::asio::placeholders::error));
    }
    void stop()
    {
        m_flag = false;
    }
    void start(int new_interval)
    {
        m_flag = true;
        m_interval = new_interval;
        m_timer.expires_from_now(boost::posix_time::millisec(m_interval));
        m_timer.async_wait(boost::bind(&MyTimer::call_func, this, boost::asio::placeholders::error));
    }
private:
    boost::function<void()> m_func;
    int m_interval;
    boost::asio::deadline_timer m_timer;
    bool m_flag;
};
void print1()
{
    std::cout << "11111" << std::endl;
}
void print2()
{
    std::cout << "22222" << std::endl;
}
boost::asio::io_service ios;
MyTimer at1(ios, print1,500);
MyTimer at2(ios, print2,500);
void threadfun()
{
    boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
    at2.stop();
    boost::this_thread::sleep(boost::posix_time::milliseconds(2000));
    at2.start(1000);
    boost::this_thread::sleep(boost::posix_time::milliseconds(3000));
    at1.stop();
    at2.stop();
}

int main()
{
    boost::thread_group thr_grp;
    thr_grp.create_thread(std::bind(threadfun));
    ios.run();
    getchar();
    return 0;
}

輸出
這裏寫圖片描述
兩個定時器創建施就開始計時,每500毫秒,執行給定的函數。在線程開始時,睡了1秒所以兩個定時器各執行了兩遍;之後停止了定時器at2的運行,睡了2秒,所以定時器at1執行了4次;之後又開始啓動定時器at2,並設置間隔時間爲1秒,而定時器at1的間隔時間還是500毫秒,所以,每定時器at1執行了兩遍,at2定時器執行一遍。

參考《Boost程序庫完全開發指南》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章