python crontab替代方案 - APScheduler&蟒蛇守护

时间:2011-10-06 16:25:17

标签: python scheduler 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个最大线程的线程池 信息:apscheduler.scheduler:调度程序已启动 DEBUG:apscheduler.scheduler:寻找要运行的工作 调查:apscheduler.scheduler:没有工作;等到添加工作 INFO:apscheduler.scheduler:添加作业“job_function(触发:间隔[0:00:30],下次运行:2011-10-06 18:30:39)”到作业商店“默认” INFO:apscheduler.scheduler:添加作业“job_function(触发:间隔[0:00:30],下次运行:2011-10-06 18:30:33”)到作业商店“默认” DEBUG:apscheduler.scheduler:寻找要运行的工作 调试:apscheduler.scheduler:下次唤醒将于2011-10-06 18:30:33(在10.441128秒内)到期

使用python-daemon, 输出为空白。为什么DaemonContext没有正确生成进程?

编辑 - 工作

在阅读python-daemon源代码后,我已将stdout和stderr添加到DaemonContext中,最后能够知道发生了什么。

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 个答案:

答案 0 :(得分:1)

我对python-daemon知之甚少,但test_log中的job_function()未定义。您引用init_schedule()的{​​{1}}也会出现同样的问题。