PyQt6 - long running thread - QThread, QTimer or QRunnable?
-
Hello,
I am facing an issue and I need some help please.
I have an app, that need a process in background to listen to a websocket and await for commands.
What would you recommend to do to run a task in background for as long as the app is running please ?Originally I had it in a QTimer as follow:
class Controller(...): # [...] def start_background_process(self): self.timer = QTimer(QApplication.instance()) self.timer.timeout.connect(self.websocket_connector.handle) self.timer.start(100) # pause a bit to avoid too much CPU usage class WSConnector(...): # [...] def handle(self): ready_to_read, ready_to_write, in_error = \ select.select((self.socket_handler.websocket.sock,), (), (), 0) while ready_to_read: # Do the job
This was working more or less ok, until I added some windows and I notice that the UI was lagging/not working while the process was doing some stuff. Altho it was handling the
QApplication.instance().quit()
very nicely and kill that timer.As a results I switched to QRunnable worker model with a QThreadpool and a
while True
to keep the worker alive. It solved the freezing UI - Yayyyh ! But I don't like very much as it adds complexity and it makes it hard to kill when the app needs to quit:class Controller(...): def __init__(self, ...): self.threadpool = QThreadPool() # [...] def start_background_process(self): self.worker = Worker(self.websocket_connector.handle) self.threadpool.start(self.worker) class WSConnector(...): # [...] def handle(self): while True: # adds more complexity but required to keep the thread alive :( ready_to_read, ready_to_write, in_error = \ select.select((self.socket_handler.websocket.sock,), (), (), 0) while ready_to_read: # Do the job time.sleep(0.1) # pause a bit to avoid too much CPU usage
-
Hi,
Since Qt has the QWebSocket class that is asynchronous, why not use it and stop adding threads to your application ?
-
Hi,
Since Qt has the QWebSocket class that is asynchronous, why not use it and stop adding threads to your application ?
-
Hi @SGaist !
Thanks for the info!
I will take a look, that sounds interesting to dig into it but it also looks like a lot of work to rework my lib that handle this particular socket app and I would be locked to Qt then :( -
B bashtian has marked this topic as solved on