PySide, Qdate; run a specific function everyday in

2019-07-25 16:32发布

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?

for example:

#run this function in everyday at 8:00 am. 
def print_something():
    print "Hello"

1条回答
做自己的国王
2楼-- · 2019-07-25 16:43

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

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_())

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.

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:

How can I hide the console window in a PyQt app running on Windows?

Namely, save the program with .pyw extension and make sure it is running with pythonw.exe, not python.exe.

查看更多
登录 后发表回答