调度程序在某些时间运行某些任务不能正常工作

时间:2013-08-12 13:51:23

标签: python datetime python-2.7 scheduled-tasks scheduler

我正在尝试让调度程序在特定时间运行脚本。

下面的代码是我自己的版本,但是当时间到达23:59:59时遇到问题并且到了00:00:01它出于某种原因没有继续空转...相反它调用一次callscripts()然后它会回到空闲状态......

from datetime import date, timedelta
from sched import scheduler
from time import time, sleep, strftime
import random

s = scheduler(time, sleep)
random.seed()

def periodically(runtime, intsmall, intlarge, function):
     ## Get current time
    currenttime = strftime('%H:%M:%S')

    ## If currenttime is anywhere between 23:40 and 23:50 then...
    if currenttime > '23:40:00' and currenttime < '23:50:00':
        ## Call clear
        clear()
        ## Update time
        currenttime = strftime('%H:%M:%S')

    ## Idle time
    while currenttime > '23:40:00' and currenttime < '23:59:59' or currenttime > '00:00:00' and currenttime < '01:30:00':
        ## Update time
        currenttime = strftime('%H:%M:%S')

    runtime += random.randrange(intsmall, intlarge)
    s.enter(runtime, 1, function, ())
    s.run()

def callscripts():
    print "Calling Functions"
    main1()
    main2()

def main1():
    print "Main1"

def main2():
    print "Main2"

def clear():
    print "Clearing"

while True:
    periodically(2, -1, +1, callscripts)

任何人都知道如何解决这个问题或知道更好的方法吗?

非常感谢AEA

1 个答案:

答案 0 :(得分:2)

这只是一个关于如何比使用字符串更有效地处理事情的概念。

import time, calendar

# Get the current time in a localtime manner (we need it for the day and year)
today = time.localtime(time.time())
# We put the day, month and year into a strftime -> localtime converter
# giving us the localtime version of 00:00:00 of today (there's cleaner version for this process)
today_strftime = time.strptime(str(today.tm_mday) + " " + time.strftime("%b") + " " + str(today.tm_year)[-2:], "%d %b %y")
# Then we take that localtime of 00:00:00 and put it into timegm which gives us the unix
# timestamp of 00:00:00 today, which we can subtract from time.time() to give us how many
# seconds of today has passed since 00:00:00.. Which we can use to compare integers with eachother (more efficient, and easy to compare)
unixtime_beginning_of_day = calendar.timegm(today_strftime)
time_passed_today = time.time() - unixtime_beginning_of_day

if time_passed_today > 3600:
    # 60sec per min * 60 minutes per hour == 3600 seconds in one hour.
    print "One hour has passed since the start of this day"