实现一个事件定时器使用boost :: ASIO [英] Implementing an event timer using boost::asio

查看:823
本文介绍了实现一个事件定时器使用boost :: ASIO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

样品code相长,但实际上它不是那么复杂: - )

The sample code looks long, but actually it's not so complicated :-)

我试图做的是,当用户调用EventTimer.Start(),它会执行回调处理程序(它被传递到构造函数)每个间隔毫秒的repeatCount 倍。

What I'm trying to do is, when a user calls EventTimer.Start(), it will execute the callback handler (which is passed into the ctor) every interval milliseconds for repeatCount times.

您只需要看看功能EventTimer ::停止()

You just need to look at the function EventTimer::Stop()

#include <iostream>
#include <string>

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

#include <ctime>
#include <sys/timeb.h>
#include <Windows.h>

std::string CurrentDateTimeTimestampMilliseconds() {
    double ms = 0.0;            // Milliseconds

    struct timeb curtime;
    ftime(&curtime);
    ms = (double) (curtime.millitm);

    char timestamp[128];

    time_t now = time(NULL);
    struct tm *tp = localtime(&now);
    sprintf(timestamp, "%04d%02d%02d-%02d%02d%02d.%03.0f",
            tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday, tp->tm_hour, tp->tm_min, tp->tm_sec, ms);

    return std::string(timestamp);
}

class EventTimer
{
public:
    static const int kDefaultInterval     = 1000;
    static const int kMinInterval         = 1;
    static const int kDefaultRepeatCount  = 1;
    static const int kInfiniteRepeatCount = -1;
    static const int kDefaultOffset       = 10;

public:
    typedef boost::function<void()> Handler;

    EventTimer(Handler handler = NULL)
        : interval(kDefaultInterval),
          repeatCount(kDefaultRepeatCount),
          handler(handler),
          timer(io),
          exeCount(-1)
    {

    }

    virtual ~EventTimer()
    {

    }

    void SetInterval(int value)
    {
//        if (value < 1)
//            throw std::exception();

        interval = value;
    }

    void SetRepeatCount(int value)
    {
//        if (value < 1)
//            throw std::exception();

        repeatCount = value;
    }

    bool Running() const
    {
        return exeCount >= 0;
    }

    void Start()
    {
        io.reset(); // I don't know why I have to put io.reset here,
                    // since it's already been called in Stop()
        exeCount = 0;

        timer.expires_from_now(boost::posix_time::milliseconds(interval));
        timer.async_wait(boost::bind(&EventTimer::EventHandler, this));
        io.run();
    }

    void Stop()
    {
        if (Running())
        {
            // How to reset everything when stop is called???
            //io.stop();
            timer.cancel();
            io.reset();

            exeCount = -1; // Reset
        }
    }

private:
    virtual void EventHandler()
    {
        // Execute the requested operation
        //if (handler != NULL)
        //    handler();
        std::cout << CurrentDateTimeTimestampMilliseconds() << ": exeCount = " << exeCount + 1 << std::endl;

        // Check if one more time of handler execution is required
        if (repeatCount == kInfiniteRepeatCount || ++exeCount < repeatCount)
        {
            timer.expires_at(timer.expires_at() + boost::posix_time::milliseconds(interval));
            timer.async_wait(boost::bind(&EventTimer::EventHandler, this));
        }
        else
        {
            Stop();
            std::cout << CurrentDateTimeTimestampMilliseconds() << ": Stopped" << std::endl;
        }
    }

private:
    int                         interval;    // Milliseconds
    int                         repeatCount; // Number of times to trigger the EventHandler
    int                         exeCount;    // Number of executed times
    boost::asio::io_service     io;
    boost::asio::deadline_timer timer;
    Handler                     handler;
};

int main()
{
    EventTimer etimer;

    etimer.SetInterval(1000);
    etimer.SetRepeatCount(1);

    std::cout << CurrentDateTimeTimestampMilliseconds() << ": Started" << std::endl;
    etimer.Start();
    // boost::thread thrd1(boost::bind(&EventTimer::Start, &etimer));

    Sleep(3000); // Keep the main thread active

    etimer.SetInterval(2000);
    etimer.SetRepeatCount(1);

    std::cout << CurrentDateTimeTimestampMilliseconds() << ": Started again" << std::endl;
    etimer.Start();
    // boost::thread thrd2(boost::bind(&EventTimer::Start, &etimer));

    Sleep(5000); // Keep the main thread active
}

/* Current Output:
20110520-125506.781: Started
20110520-125507.781: exeCount = 1
20110520-125507.781: Stopped
20110520-125510.781: Started again
 */

/* Expected Output (timestamp might be slightly different with some offset)
20110520-125506.781: Started
20110520-125507.781: exeCount = 1
20110520-125507.781: Stopped
20110520-125510.781: Started again
20110520-125512.781: exeCount = 1
20110520-125512.781: Stopped
 */

我不知道为什么,我打电话给EventTimer ::开始()的第二次根本不工作。我的问题是:

I don't know why that my second time of calling to EventTimer::Start() does not work at all. My questions are:


  1. 我应该怎么做
    EventTimer ::停止(),以重置
    一切都使得下一次
    调用Start()是否行得通呢?

  1. What should I do in EventTimer::Stop() in order to reset everything so that next time of calling Start() will work?

还有什么我需要修改?

如果我用另一个线程来启动EventTimer ::开始()(见注释code在主函数),什么时候该线程实际上退出?

If I use another thread to start the EventTimer::Start() (see the commented code in the main function), when does the thread actually exit?

感谢。

彼得

推荐答案

我理解了它,但我不知道为什么,我不得不把 io.reset()开始(),因为它已经被称为停止()。

I figured it out, but I don't know why that I have to put io.reset() in Start(), since it's already been called in Stop().

请参阅更新code在后。

See the updated code in the post.

这篇关于实现一个事件定时器使用boost :: ASIO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆