保持Python脚本运行的最佳方法是什么?

2024-09-27 09:33:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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循环。我真的不知道这是不是最好的,更不用说Python式的方法了。有没有更好的方法?欢迎所有提示!在


Tags: 方法fromimporttruetimedefsleepstart
2条回答

尝试使用阻塞调度程序。apsched.开始()只会阻止。你必须在开始前设置好。在

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

apsched = BlockingScheduler()

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

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

apsched.start() # will block

试试这个代码。它将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()

用法:

^{pr2}$

相关问题 更多 >

    热门问题