[英]How do i schedule a program in python
我想要一個使我的主程序每周運行兩次的程序...我嘗試使用crontab,但由於在Windows上進行編程(結果很困難)而無法運行,並且我希望該程序在視窗
我的主程序沒有做任何瘋狂的事情,只是檢查一個excel文件並在tkinter窗口中提供一些信息
我還閱讀了有關Windows中的任務計划程序的信息,但是我想在程序中自由編輯或刪除計划的事件...有any help
嗎?
有一個簡單的方法可以做到,親愛的朋友! 首先,您應該在計算機上使用Linux OS安裝虛擬機(使用virtualbox和vmware)。 您可以只使用linux crontab !
cronb -e
並使用您最喜歡的編輯器,並編寫此行
0 8 * * 3,7 python /path/to/dir/test.py
您的代碼將在周三和周日的08:00執行。
您可以使用Task Scheduler API以編程方式創建計划的任務。 例如: https : //ziade.org/2007/11/01/scheduling-tasks-in-windows-with-pywin32/
如果不想讓pywin32成為此項目的依賴項,則可以使用子進程庫通過調用schtask.exe來進行更簡單的調度。
使用Croniter解決。 它適用於Linux。 在Windows上嘗試一下。
from datetime import datetime, timedelta #for Scheduler
import time
from croniter import croniter
# Class for Scheduling
class schedule_fun():
def starter(self):
nextRunTime = self.getNextCronRunTime(schedule)
while True:
roundedDownTime = self.roundDownTime()
if (roundedDownTime == nextRunTime):
global timestamp
timestamp = datetime.now().strftime("%B %d %Y, %H:%M:%S")
#For setting variables with values
print ("Hi, I am Steven")
nextRunTime = self.getNextCronRunTime(schedule)
elif (roundedDownTime > nextRunTime):
print("error")
# We missed an execution. Error. Re initialize.
nextRunTime = self.getNextCronRunTime(schedule)
self.sleepTillTopOfNextMinute()
# Round time down to the top of the previous minute
def roundDownTime(self,dt=None, dateDelta=timedelta(minutes=1)):
roundTo = dateDelta.total_seconds()
if dt == None : dt = datetime.now()
seconds = (dt - dt.min).seconds
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + timedelta(0,rounding-seconds,-dt.microsecond)
# Get next run time from now, based on schedule specified by cron string
def getNextCronRunTime(self,schedule):
return croniter(schedule, datetime.now()).get_next(datetime)
# Sleep till the top of the next minute
def sleepTillTopOfNextMinute(self):
t = datetime.utcnow()
sleeptime = 60 - (t.second + t.microsecond/1000000.0)
time.sleep(sleeptime)
# Program starts here!!!!
if __name__ == '__main__':
schedule = '*/1 * * * *'
scl = schedule_fun()
scl.starter()
每個DAG可能有也可能沒有時間表,該時間表會通知如何創建DAG運行。 schedule_interval被定義為DAG參數,並且最好接收cron表達式作為str或datetime.timedelta對象。 或者,您也可以使用以下cron“預設”之一
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.