整个故事有点复杂,它很大程度上取决于你想用你的剧本做什么。
例如,此代码可以正常工作:import threading
import schedule
import time
import datetime
import sys
def test():
print('{} This is a test'.format(datetime.datetime.now())) #this works ok
def exit():
print('{} Now the system will exit '.format(datetime.datetime.now())) #this works ok
sys.exit()
schedule.every().day.at("09:57").do(test)
schedule.every().day.at('09:58').do(exit)
while True:
schedule.run_pending()
time.sleep(1)
您将在终端中看到“测试消息”,一分钟后您将看到“退出消息”,它实际上终止了脚本。在
但如果您在上面的函数测试中应用一些循环,如:
^{pr2}$
然后脚本将不会退出。
实际上,函数exit甚至不会被调用,因为Python被函数测试中的while循环所捕获,并将一直持续下去。在
Schedule文档指出,调度的作业是串行调用的,因此,如果前一个作业没有完成,下一个作业实际上就不会开始。在
我怀疑您的目的是让某个函数在10:00连续运行,而您希望在12:30强制停止该函数。如果不是这样的话,你的主要功能会在他完成任务后立即退出,你不需要一个时间框架。在
在这种情况下,为了绕过Python&Schedule的序列化方式,您需要使用线程。在import threading
import schedule
import time
import datetime
import sys
def doit(stop_event, arg):
while not stop_event.wait(1):
#By wait(1) you repeat the loop every 1 sec.
#Applying wait(0) , loops run immediatelly until to be stopped by stop_event
print ("working on %s" % arg)
print("Stopping as you wish.")
def startit():
global pill2kill
global t
pill2kill = threading.Event()
t = threading.Thread(target=doit, args=(pill2kill, "task"))
t.start()
def stopit():
global pill2kill
global t
pill2kill.set()
t.join()
#startit() #Manual call for Testing
#time.sleep(5) #Wait 5 seconds
#stopit() #Manual call for Testing
schedule.every().day.at("12:48").do(startit)
schedule.every().day.at('12:49').do(stopit)
#schedule.every().day.at("12:50").do(startit) #Uncomment this to recall it for testing
#schedule.every().day.at('12:51').do(stopit) #Unocmment this to recall it for testing
while 1:
schedule.run_pending()
time.sleep(1)
PS:顺便说一下,快速查看一下Python Schedule Lib的源代码,似乎整个故事都是通过捕获整个脚本并不断进行比较来完成的日期。现在()的日期设置为运行作业。这个逻辑可以用两个默认命令和一个无限主循环来重建,以连续比较日期(就像Schedule Lib一样)。
This post有一些很好的代码片段来制作自己的cron作业,但是仅仅为了测试这个简化的脚本,在没有外部lib的情况下也可以很好地工作日期时间。现在在所需的启动/停止帧内。在from datetime import datetime
import time
def test():
global hasrun
print('{} This is a test'.format(datetime.now()))
time.sleep(5)
hasrun=True
year,month,day,hour,minute=2016,12,23,15,55
hasrun=False
now=datetime.now()
print "Now the time is :", now
jobstart=datetime(year,month,day,hour,minute)
jobstop=datetime(year,month, day,hour,minute+1)
print "Job will run at: ", jobstart
print "Job will finish at: ", jobstop
#print datetime.now() - jobstart
while True:
while ((datetime.now() > jobstart) and (datetime.now() < jobstop )):
test()
else:
print('{} Please Wait...'.format(datetime.now()))
if hasrun:
# day=day+1
minute=minute+2 #Just for Testing
jobstart=datetime(year,month,day,hour,minute)
jobstop=datetime(year,month, day,hour,minute+1)
print "the job will run again ", jobstart
print "and will finish at ", jobstop
hasrun=False
time.sleep(5)