使用croniter根据计划时间运行python脚本

时间:2019-02-07 05:46:46

标签: python cron

我有一个功能可以做一些工作。该代码应根据计划重复执行。我使用了Croniter模块。时间表应采用cron类型的语法。它每分钟工作一次。但是几秒钟不起作用。我在计划表中最后增加了几秒钟,但它说的是小板语法是不可接受的。如何在语法中增加秒数以使其也能工作数秒? 这是我的代码。

import yaml
from croniter import croniter
from datetime import datetime, timedelta
import time

def fun():
    for i in items:
        print (i)
def roundDownTime(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)
def getNextCronRunTime(schedule):
    return croniter(schedule, datetime.now()).get_next(datetime)
def sleepTillTopOfNextMinute():
    t = datetime.utcnow()
    sleeptime = 60 - (t.second + t.microsecond/1000000.0)
    time.sleep(sleeptime)

items =[2,4,6,7]
schedule =  "*/1 * 7 2 * "
nextRunTime = getNextCronRunTime(schedule)
while True:
     roundedDownTime = roundDownTime()
     if (roundedDownTime == nextRunTime):
         fun()
         nextRunTime = getNextCronRunTime(schedule)
     elif (roundedDownTime > nextRunTime):
         # We missed an execution. Error. Re initialize.
         nextRunTime = getNextCronRunTime(schedule)
     sleepTillTopOfNextMinute()

0 个答案:

没有答案