from PyQt5.QtCore import QTimer def periodic_task(): print('This function is executed every 2 seconds') # Create a QTimer instance timer = QTimer() # Connect a function to the QTimer timeout signal timer.timeout.connect(periodic_task) # Start the timer timer.start(2000) # 2 seconds in milliseconds
from PyQt5.QtCore import QTimer, QDateTime from PyQt5.QtWidgets import QApplication, QLabel app = QApplication([]) # Create a QLabel label = QLabel('Time goes here') def update_time(): current_time = QDateTime.currentDateTime().toString('hh:mm:ss') label.setText(current_time) # Create a QTimer instance timer = QTimer() # Connect a function to the QTimer timeout signal timer.timeout.connect(update_time) # Start the timer timer.start(1000) # 1 second in milliseconds # Show the QLabel label.show() # Run the application event loop app.exec()In brief, these examples demonstrate how the QTimer class can be used in PyQt5 to create a periodic task. The first example executes a function every 2 seconds, while the second example updates a widget with the current time once every second. The PyQt5 package library contains this QTimer class for scheduling tasks in a PyQt5 application.