Search code examples
c++timerpoco

Poco Timer with callback from same class


I have a simple class which uses Poco Timer:

MyClass::MyClass(){
 Timer timer(250,5000);
 TimerCallback<MyClass> callback(*this, &MyClass::onTimer);
 timer.start(callback);
}

MyClass::onTimer(){
  cout <<"Tick"<<endl;
}

Obviously, the code for callback initialization is incorrect. What is the correct way to call a function from within the same class (this) with TimerCallback?


Solution

  • You can use Timer as member of MyClass:

    MyClass {
      //...
      Timer timer;
    };
    

    then construct timer object on initialization list to set intervals in ctor of Timer

    MyClass::MyClass() : timer(250,5000) { // <--
      TimerCallback<MyClass> callback(*this, &MyClass::onTimer);
      timer.start(callback);
    }
    

    or use setPeriodicInterval and setStartInterval

      MyClass::MyClass() {
       timer.setStartInterval(500);
       timer.setPeriodicInterval(2500);
       TimerCallback<MyClass> callback(*this, &MyClass::onTimer);
       timer.start(callback);
      }