保持Python脚本运行的最佳方法?
我正在使用APScheduler运行一些定期任务,如下所示:保持Python脚本运行的最佳方法?,python,cron,daemon,apscheduler,Python,Cron,Daemon,Apscheduler,我正在使用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(d
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)
因为这个脚本结束时,interval_作业结束,所以我只添加了end
while True
循环。我真的不知道这是否是最好的方法,更不用说蟒蛇式的方法了。有没有“更好”的方法?欢迎所有提示 试试这段代码。它作为守护进程运行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
尝试使用阻塞调度程序。apsched.start()只会阻塞。你必须在开始之前设置好它 编辑:响应注释的一些伪代码
apsched = BlockingScheduler()
def doSomethingRecurring():
pass # Do something really interesting here..
apsched.add_job(doSomethingRecurring, trigger='interval', seconds=2)
apsched.start() # will block
我对你的回答有点困惑。如您所见,我实际上使用的是
apsched.start()
。你是在暗示我必须“在开始之前设置好”。你能解释一下你的意思吗?欢迎使用一些示例代码!