Python: How to use QTimer to run function many times with the same interval.
If you want to execute some function with delay you could use time.sleep() but it blocks rest of code. You could also run it in separated thread and then it not blocks rest of code. You can also try to use modules like shedule, shed to manage tasks or you can even use external program like cron on Linux to resolve this problem.
But when you works with some GUI framework then usually it have some function to run code with delay without locking rest of code.
PyQt has special class QTimer to run function single time with delay or to run function many times with the same time intervals.
If function is small and fast then it doesn't block rest of code.
In this example it is used to update text on QLabel every 1 second (1000ms) and display currect time.
import sys from PyQt5.QtCore import Qt, QTimer from PyQt5 import QtWidgets import datetime def display_time(): current_time = datetime.datetime.now().strftime('%Y.%m.%d - %H:%M:%S') label.setText(current_time) print('current_time:', current_time) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QMainWindow() # some GUI in window label = QtWidgets.QLabel(window, text='???', alignment=Qt.AlignCenter) window.setCentralWidget(label) window.show() # timer which repate function `display_time` every 1000ms (1s) timer = QTimer() timer.timeout.connect(display_time) # execute `display_time` timer.setInterval(1000) # 1000ms = 1s timer.start() sys.exit(app.exec())
Notes:
Stackoverflow: How Python QTimer and graphical user interface (GUI) applications with Qt works together?
EDIT:
Example which try to run two times. Usually it would work but here one of functions execute long-running code and it blocks other code. It would need to run it in separated thread (inside QTimer)
import sys from PyQt5.QtCore import Qt, QTimer from PyQt5 import QtWidgets import datetime import time def display_time(): current_time = datetime.datetime.now().strftime('%Y.%m.%d - %H:%M:%S') label.setText(current_time) print('current_time:', current_time) def long_job(): for x in range(10): print('Job:', x) time.sleep(1) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QMainWindow() # some GUI in window label = QtWidgets.QLabel(window, text='???', alignment=Qt.AlignCenter) window.setCentralWidget(label) window.show() # timer which repate function `display_time` every 1000ms (1s) timer = QTimer() timer.timeout.connect(display_time) # execute `display_time` timer.setInterval(1000) # 1000ms = 1s timer.start() timer2 = QTimer() timer2.timeout.connect(long_job) # execute `display_time` timer2.setInterval(1000) # 1000ms = 1s timer2.start() sys.exit(app.exec())
