Poco 计时器示例

Rya*_*ins 4 c++ linux timer poco

以下是一位同事提出的问题,在网上搜了一下,没有找到一个好的答案后,这似乎是一个很好的问题:

我在我的嵌入式代码中使用 POCO 计时器(在 Linux 上运行)。计时器是 Foundation 组件的一部分。定时器具有三个基本功能:

Timer.start();
Timer.stop();
Timer.restart();
Run Code Online (Sandbox Code Playgroud)

我试图停止然后重新启动我的计时器,但我无法让它工作... ...我已经查看了所有 POCO 示例和示例,并且 timer.restart() 没有任何内容。

有没有人对此有任何见解,或者停止和重新启动计时器的工作代码示例?即使回调函数没有运行,计时器也会启动和停止,但重启似乎不起作用。

Rya*_*ins 7

好的,自从提出这个问题以来,我继承了我同事的项目并自己找到了答案。

//use restart for an already running timer, to restart it
Timer.restart();
Run Code Online (Sandbox Code Playgroud)

如果你的定时器已经停止,需要重启,你需要先重置周期间隔,下面是Poco的例子,里面加了几行我自己的。这将编译并重新启动计时器。

#include "Poco/Timer.h"
#include "Poco/Thread.h"
#include "Poco/Stopwatch.h"
#include <iostream>


using Poco::Timer;
using Poco::TimerCallback;
using Poco::Thread;
using Poco::Stopwatch;


class TimerExample
{
public:
        TimerExample()
        {
                _sw.start();
        }

        void onTimer(Timer& timer)
        {
                std::cout << "Callback called after " << _sw.elapsed()/1000 << "      milliseconds." << std::endl;
        }

private:
        Stopwatch _sw;
};


int main(int argc, char** argv)
{    


    TimerExample example;
    TimerCallback<TimerExample> callback(example, &TimerExample::onTimer);

    Timer timer(250, 500);

    timer.start(callback);

    Thread::sleep(5000);

    timer.stop();

    std::cout << "Trying to restart timer now" << std::endl;

    timer.setStartInterval(250);
    timer.setPeriodicInterval(500);
    timer.start(callback);

    Thread::sleep(5000);

    timer.stop();


    return 0;
 }
Run Code Online (Sandbox Code Playgroud)