0

我正在尝试制作一个调度程序来在特定时间运行脚本。

下面的代码是我自己的版本,但是当时间到达 23:59:59 并跨越到 00:00:01 时出现问题,由于某种原因它不会继续空闲......而是调用调用脚本() 一次,然后它会回到空转...

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

4

1 回答 1

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"
于 2013-08-12T14:31:21.887 回答