欢迎访问宙启技术站
智能推送

使用PyQt5.QtCore.QTimer.singleShot()实现定时重复执行任务

发布时间:2023-12-23 17:40:46

使用PyQt5.QtCore.QTimer.singleShot()方法可以实现定时重复执行任务。该方法支持在指定的时间间隔后执行一个函数,并且可以重复执行多次。

下面是一个使用PyQt5.QtCore.QTimer.singleShot()方法实现定时重复执行任务的例子:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtCore import QTimer

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.label = QLabel("Task executed 0 times", self)
        self.label.setGeometry(50, 50, 200, 50)

        self.counter = 0

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.execute_task)
        self.timer.start(1000)  # 每隔1秒执行一次任务

    def execute_task(self):
        self.counter += 1
        self.label.setText(f"Task executed {self.counter} times")

        if self.counter >= 10:
            self.timer.stop()
            self.label.setText("Task completed")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

在这个例子中,我们创建了一个主窗口,里面包含一个标签用来显示任务执行的次数。在execute_task()方法中,我们将计数器加1,并更新标签文本展示当前的执行次数。当任务执行次数达到10次时,我们调用timer.stop()方法来停止定时器,并将标签文本设置为"Task completed"。

__init__()方法中,我们创建了一个定时器,通过指定时间间隔为1000ms(1秒)来设置定时器重复执行任务的频率。然后我们将定时器的timeout信号连接到execute_task()方法,这样每当定时器触发timeout信号时,execute_task()方法就会被调用一次。

最后,在main函数中,我们创建了一个QApplication实例,并显示主窗口,然后进入主事件循环中。

运行这个例子,你会看到窗口中的标签每隔1秒更新一次,显示任务执行的次数。当执行次数达到10次时,定时器停止,标签的文本变为"Task completed"。