Python 的 crontab 替代 - APScheduler 和 python-daemon
我在使用 python-daemon 1.6 和 APScheduler 一起管理任务列表时遇到了一些问题。
(这个调度器需要定期在特定的时间运行这些任务,精确到秒)
正常工作(直到按下 Ctrl+C),
from apscheduler.scheduler import Scheduler
import logging
import signal
def job_function():
print "Hello World"
def init_schedule():
logging.basicConfig(level=logging.DEBUG)
sched = Scheduler()
# Start the scheduler
sched.start()
return sched
def schedule_job(sched, function, periodicity, start_time):
sched.add_interval_job(job_function, seconds=periodicity, start_date=start_time)
if __name__ == "__main__":
sched = init_schedule()
schedule_job(sched, job_function, 120, '2011-10-06 12:30:09')
schedule_job(sched, job_function, 120, '2011-10-06 12:31:03')
# APSScheduler.Scheduler only works until the main thread exits
signal.pause()
# Or
#time.sleep(300)
示例输出:
INFO:apscheduler.threadpool:启动了线程池,核心线程数为0,最大线程数为20
INFO:apscheduler.scheduler:调度器已启动
DEBUG:apscheduler.scheduler:正在寻找要运行的任务
DEBUG:apscheduler.scheduler:没有任务;等待添加任务
INFO:apscheduler.scheduler:将任务 "job_function (触发器: interval[0:00:30], 下次运行时间: 2011-10-06 18:30:39)" 添加到任务存储 "default"
INFO:apscheduler.scheduler:将任务 "job_function (触发器: interval[0:00:30], 下次运行时间: 2011-10-06 18:30:33)" 添加到任务存储 "default"
DEBUG:apscheduler.scheduler:正在寻找要运行的任务
DEBUG:apscheduler.scheduler:下次唤醒时间为 2011-10-06 18:30:33(在10.441128秒后)
使用 python-daemon 时, 输出是空白的。为什么 DaemonContext 没有正确生成进程呢?
编辑 - 解决了
在阅读了 python-daemon 的源代码后,我在 DaemonContext 中添加了 stdout 和 stderr,最终我才明白发生了什么。
def job_function():
print "Hello World"
print >> test_log, "Hello World"
def init_schedule():
logging.basicConfig(level=logging.DEBUG)
sched = Scheduler()
sched.start()
return sched
def schedule_job(sched, function, periodicity, start_time):
sched.add_interval_job(job_function, seconds=periodicity, start_date=start_time)
if __name__ == "__main__":
test_log = open('daemon.log', 'w')
daemon.DaemonContext.files_preserve = [test_log]
try:
with daemon.DaemonContext():
from datetime import datetime
from apscheduler.scheduler import Scheduler
import signal
logging.basicConfig(level=logging.DEBUG)
sched = init_schedule()
schedule_job(sched, job_function, 120, '2011-10-06 12:30:09')
schedule_job(sched, job_function, 120, '2011-10-06 12:31:03')
signal.pause()
except Exception, e:
print e
1 个回答
我对python-daemon了解不多,但在job_function()
里面,test_log
这个东西没有定义。init_schedule()
里面也有同样的问题,因为你提到了Schedule
,但它没有被定义。