Unsolved QTimer
-
Hello,
I am having implementation considerations. I am trying to create a thread that executes a function periodically. I am using the Worker class that holds the function I would like to execute periodically.
The issue I am having is whether or not I should use the QTimer within my worker object, or if I should use the timer in the main app to periodically execute this function from the worker object.
Implementation 1:
main.cppQTimer m_timer;
worker *workerObject = new worker()
QThread *workerThread = new QThread();
workerObject->moveToThread(workerThread);
connect(&m_timer, SIGNAL(timeout()), workerObject, SLOT(function()))
m_timer.start(2000);
workerThread->start();This runs as intended and executes the function in worker periodically.
Implementation 2:
main.cppworker *workerObject = new worker()
QThread *workerThread = new QThread();
workerObject->moveToThread(workerThread);
workerThread->start()in the constructor of the Worker Class:
QTimer m_timer;
connect(&m_timer, SIGNAL(timeout()), this, SLOT(function())));
m_timer.start(2000);&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
both of these methods work, they execute this function in a separate thread periodically. I was hoping to figure out the pros/cons of using the timer in the worker object vs the main app.
-
Hi,
Having your QTimer within the worker makes it self-contained and allows you to instanciate several workers without having to modify your main function.
-
@SGaist Thank you for the response.
I will only need to instantiate this worker once so that is not my primary concern.
When I check the current threads running on my systems -
Implementation 1 says my thread is "RUNNING"
implementation 2 says "SIGWAIT". I am assuming the SIGWAIT is waiting for the timer to timeout(), which bring me to the next point.I would theoretically want my separate thread to be waiting until it is needed vs having the thread actively "RUNNING". Based of this, I would assume implementation 2 is more ideal for my situation. I was hoping to get some reassurance from these forums and/or pros/cons.
-
Well, you should rather have a proper API to manage starting the timer of your worker object at the correct time. It's a question of good encapsulation and object responsibility.