保持Python脚本持续运行的最佳方法?

0 投票
2 回答
4223 浏览
提问于 2025-04-19 13:35

我正在使用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)

因为这个interval_job会在脚本结束时停止,所以我简单地加了一个结尾的while True循环。我其实不太确定这样做是否是最好的,甚至是否符合Python的风格。有没有什么“更好”的方法呢?欢迎任何建议!

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
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

撰写回答