Nominate our 2022 Qt Champions!

What is the best way to implement a looped function with a timer?

  • Basically I have a function that has to execute with a certain frequency(something like 50 Hz). I can either implement it with QThread, using an infinite loop() with Qthread::msleep(timestep) in the middle OR I could use a QTimer, sending a signal to loop() at fixed timestep. What is the "proper" way to deal with this? Which one will be more efficient, computationally?

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    It depends partly on how long your operation takes.

    If you take the QTimer approach, you don't need to implement a loop() function, just a function that does what you need. You can use the worker object approach described in QThread's documentation. You also don't need a QTimer, QObject has startTimer + timerEvent that you can use for that purpose. That's up to your personal taste which one you're more comfortable to use.

    Hope it helps

  • @SGaist OK, so there is not much difference and it's up to me then. It helps, thank you!

  • Moderators

    @ptitz said:

    I can either implement it with QThread, using an infinite loop() with Qthread::msleep(timestep) in the middle

    Please, don't do that, it's bad programming. How are you going to stop the thread, by killing it? If you want to use the low-level threading API, create your worker QObject move it to the thread and signal it with a timer event.

  • Keep in mind that every event handler that you'll run in the main thread ads up to the time the main event loop requires to complete (and this directly impacts on the delay between the moment an event is detected and the time it gets to be processed). My personal approach is to use a different thread for each and every event handler in an application whenever possible (i.e. whenever the event handlers are truly independent) if there is a chance that said event handlers may take a relatively long time to complete.

  • Lifetime Qt Champion

    @ptitz Depends on which difference you are talking about, do you mean between a QTimer and using the startTimer/timerEvent ? If so, then yes, the difference is pretty minor.

    Otherwise, I agree with @kshegunov, for tasks that should run at regular interval, the worker object approach is better but you also have to be sure that the task can complete between two timeouts.

Log in to reply