Python sched 调度器和重启
我读过关于Python的sched
(任务调度器),它的工作方式类似于cron。
不过我有个问题:
- 假设我安排一个函数每两小时运行一次,但在这段时间我的系统关机了,然后我重新启动系统……
调度器会自动启动并在两小时后运行这个函数吗?还是说我需要在关机后重新启动它?
sched
的工作方式像守护进程一样吗?
2 个回答
0
如果是这样的话:
那么在系统重启后,这个也能继续工作吗?
答案是:不可以。那么,为什么turbogear的调度器可以在cron中使用cronos呢?turbogear中安排的事件在系统重启后也会消失。
如果我说错了,请纠正我。
import time
import sched
import datetime
import threading
import calendar
#from datetime import datetime
class test:
def __init__(self):
self.name = ''
def getSec(self):
now = datetime.datetime.now()
print "now - ", now
currentYear = now.year
currentMonth = now.month
currentDay = now.day
currentHour = now.hour
currentMinute = now.minute
currentSecond = now.second
currentMicroseconds = now.microsecond
command = "python runbackup.py"
print "command is - ", command
print "currentMinute - ", currentMinute
print "currentSecond - ", currentSecond
# current time
a = datetime.datetime(currentYear, currentMonth, currentDay, currentHour, currentMinute, currentSecond, currentMicroseconds)
last_date_of_current_month = calendar.monthrange(currentYear, currentMonth)[1]
print "last_date_of_current_month - ", last_date_of_current_month
b = datetime.datetime(currentYear, currentMonth, int(last_date_of_current_month), 23, 59, 59, 000000)
#b = datetime.datetime(currentYear, currentMonth, int(29), 18, 29, 00, 000000)
#print "date time of b is - %s %s " % (18, 29)
c = b-a
print "c is - ", c
time.sleep(1)
scheduler = sched.scheduler(time.time, time.sleep)
#scheduler.cancel(e1)
sec = c.seconds
print "second - ", sec
print "scheduler entered."
e1 = scheduler.enter(sec, 1, self.getSec, ())
t = threading.Thread(target=scheduler.run)
print "thread started."
print "======================================"
t.start()
#scheduler.cancel(e1)
#print "canceled."
return True
if __name__=='__main__' :
obj = test()
obj.getSec()
1
这三个问题的答案都是不。
sched和cron是不同的东西。sched需要一个通用的计时器或计数器函数,还有一个延迟函数,它可以让你在特定时间后安排一个函数的调用(这个特定时间是由你的计时器函数定义的)。
如果你关闭了程序,它就不会继续运行,除非你通过写入文件或数据库来保持状态。这种做法比较复杂,使用cron会更好一些。
sched是基于事件工作的,但不是在后台运行的。所以,它并不完全是一个守护进程,不过你可以通过操作系统的功能把它放到后台运行,变成一个守护进程。