0

我正在使用 APScheduler 运行一些重复性任务,如下所示:

from apscheduler.scheduler import Scheduler
from time import time, sleep

apsched = Scheduler()
apsched.start()

def doSomethingRecurring():
    pass  # Do something really interesting here..

apsched.add_interval_job(doSomethingRecurring, seconds=2)

while True:
    sleep(10)

因为这个脚本结束时间隔作业结束,所以我只是添加了结束while True循环。我真的不知道这是否是最好的,更不用说pythonic方式来做到这一点了。有没有“更好”的方式来做到这一点?欢迎所有提示!

4

2 回答 2

1

试试这个代码。它运行一个 python 脚本作为守护进程:

import os
import time

from datetime import datetime
from daemon import runner


class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path = '/var/run/mydaemon.pid'
        self.pidfile_timeout = 5

    def run(self):
        filepath = '/tmp/mydaemon/currenttime.txt'
        dirpath = os.path.dirname(filepath)
        while True:
            if not os.path.exists(dirpath) or not os.path.isdir(dirpath):
                os.makedirs(dirpath)
            f = open(filepath, 'w')
            f.write(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'))
            f.close()
            time.sleep(10)


app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

用法:

> python mydaemon.py
usage: md.py start|stop|restart
> python mydaemon.py start
started with pid 8699
> python mydaemon.py stop
Terminating on signal 15
于 2014-09-03T10:40:17.267 回答
1

尝试使用阻塞调度程序。apsched.start() 只会阻塞。您必须在开始之前进行设置。

编辑:响应评论的一些伪代码。

apsched = BlockingScheduler()

def doSomethingRecurring():
    pass  # Do something really interesting here..

apsched.add_job(doSomethingRecurring, trigger='interval', seconds=2)

apsched.start() # will block
于 2014-09-03T10:41:34.780 回答