Search code examples
c++qtqtimer

Call a function n times with an interval of n seconds


I want to simply call a function 4 times within an interval of 10 seconds. This calls it only once

    QTimer *timer = new QTimer(this);
    timer->setSingleShot(true);
    connect(timer, SIGNAL(timeout()), this, SLOT(myFunction()));
    timer->start(10000);

And if I get rid of the setSingleShot method, it will be called forever. Is there a built in way to call it only n times. I couldn't find it in the Qt documentation.


Solution

  • The brute-force, non-scalable way: start four timers.

    A more practical way is to have the callback keep track of how many times it has been called, then stop the timer on the fourth call.