Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Poco Timer Example

The following was asked by a coworker and after poking around the internet and not finding a good answer it seemed like a good question for here:

I am using POCO timers in my embedded code(running on Linux). The timers are a part of the Foundation component. The timers have three basic functions:

Timer.start();
Timer.stop();
Timer.restart();

I am trying to stop and then restart my timers and I can not get it to work... ...I have looked at all of the POCO samples and examples and there is nothing for timer.restart().

Does anyone have any insight into this, or a working code example stopping and restarting the timers? Even though the callback function isn't running, the timer will start and stop, but restart doesn't seem to be working.

like image 941
Ryan Higgins Avatar asked Mar 23 '23 06:03

Ryan Higgins


1 Answers

Ok, since asking this question I've inherited my coworker's project and found the answer myself.

//use restart for an already running timer, to restart it
Timer.restart();

If your timer is already stopped and you need to restart, you need to reset the periodic interval first, the following is the Poco example with a few lines of my own added to it. This compiles and restarts a timer.

#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;
 }
like image 145
Ryan Higgins Avatar answered Apr 06 '23 08:04

Ryan Higgins