Skip to content Skip to sidebar Skip to footer

Pyside, Qdate; Run A Specific Function Everyday In A Specific Time

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 functio

Solution 1:

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=2016month=4day=23hour=12minute=40    
alarmDateTime = QtCore.QDateTime(int(year), int(month), int(day), int(hour), int(minute), int(0))   
#Wait for alarm totriggerat appropriate time (checkevery5 seconds)
while QtCore.QDateTime.currentDateTime() < alarmDateTime:
    time.sleep(5)

#Once alarm is triggered, createandshow QLabel, andthen 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.

Post a Comment for "Pyside, Qdate; Run A Specific Function Everyday In A Specific Time"