PySide、Qdate;每天在特定时间运行特定功能 [英] PySide, Qdate; run a specific function everyday in a specific time
问题描述
我正在尝试使用 PySide 开发 gui,我想知道是否有办法在 Python (QDate
) 中调用函数并在特定日期和时间运行它?
I am trying to develop a gui with PySide and I wonder if there is a way to call a function in Python (QDate
) and run it in a specific date and time?
例如:
#run this function in everyday at 8:00 am.
def print_something():
print "Hello"
推荐答案
这里是改编自 Summerfield 的 PyQt 书籍第 4 章的脚本,他的 alert.py
示例.可在此处免费在线获取:http://www.informit.com/articles/article.aspx?p=1149122
Here is a script adapted from Chapter 4 of Summerfield's PyQt book, his alert.py
example. It is available free online here:
http://www.informit.com/articles/article.aspx?p=1149122
基本上你设置一个目标QDateTime
,然后你可以通过将目标与currentQDateTime
进行比较来触发你想要的任何可调用:
Basically you set a target QDateTime
, and then you can trigger whatever callable you want by comparing the target to currentQDateTime
:
from PySide import QtCore, QtGui
import sys
import time
#Prepare alarm
alarmMessage = "Wake up, sleepyhead!"
year = 2016
month = 4
day = 23
hour = 12
minute = 40
alarmDateTime = QtCore.QDateTime(int(year), int(month), int(day), int(hour), int(minute), int(0))
#Wait for alarm to trigger at appropriate time (check every 5 seconds)
while QtCore.QDateTime.currentDateTime() < alarmDateTime:
time.sleep(5)
#Once alarm is triggered, create and show QLabel, and then exit application
qtApp = QtGui.QApplication(sys.argv)
label = QtGui.QLabel(alarmMessage)
label.setStyleSheet("QLabel { color: rgb(255, 0, 0); font-weight: bold; font-size: 25px; \
background-color: rgb(0,0,0); border: 5px solid rgba(0 , 255, 0, 200)}")
label.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.WindowStaysOnTopHint)
label.show()
waitTime = 10000 #in milliseconds
QtCore.QTimer.singleShot(waitTime, qtApp.quit)
sys.exit(qtApp.exec_())
这个有一个 QLabel 在你想要的日期和时间弹出,但这是任意的.你可以让它做任何你想做的事.如果您希望它每天在同一时间运行,则必须对其进行适当修改,但这应该足以让您开始使用 QDateTime
来触发事件.
This one has a QLabel pop up at the day and time you want, but that is arbitrary. You could have it do anything you want. If you want it to run every day at the same time, you would have to modify it appropriately, but this should be enough to get you started using QDateTime
to trigger events.
请注意,如果您在 Windows 中工作并且希望在后台运行它,而不会在屏幕上显示命令窗口,请按照此处的建议进行操作:
Note if you are working in Windows and you want to run it in the background, without a command window showing on your screen, then follow the advice here:
如何我可以在 Windows 上运行的 PyQt 应用程序中隐藏控制台窗口吗?
即,使用 .pyw
扩展名保存程序,并确保它使用 pythonw.exe
而不是 python.exe
运行.
Namely, save the program with .pyw
extension and make sure it is running with pythonw.exe
, not python.exe
.
这篇关于PySide、Qdate;每天在特定时间运行特定功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!