如何在后台制作 Python apscheduler 运行

How to make Python apscheduler run in background

我想在后台制作Python一个ps调度程序运行,这是我的代码:

from apscheduler.schedulers.background import BackgroundScheduler, BlockingScheduler  
from datetime import datetime  
import logging  
import sys

logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)

def singleton(cls, *args, **kw):
    instances = {}

    def _singleton(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]

    return _singleton

@singleton
class MyScheduler(BackgroundScheduler):
    pass

def simple_task(timestamp):  
    logging.info("RUNNING simple_task: %s" % timestamp)

scheduler = MyScheduler()
scheduler.start()

scheduler.add_job(simple_task, 'interval', seconds=5, args=[datetime.utcnow()])

当我运行命令时:

look:Python look$ python itger.py

我刚得到这个:

INFO:apscheduler.scheduler:调度程序已启动 DEBUG:apscheduler.scheduler:正在寻找 运行 的工作 DEBUG:apscheduler.scheduler:没有工作;等待添加作业 INFO:apscheduler.scheduler:已将作业 "simple_task" 添加到作业存储区 "default"

和ps:

ps -e | grep python

我刚刚得到54615 ttys000 0:00.00 grep python

我的问题是如何在后台设置代码 运行 我可以看到它正在 运行ning 或每 5 秒打印一次日志所以代码显示?

BackgroundScheduler 在后台线程中运行,在这种情况下,我猜,不会阻止应用程序主要威胁终止。

尝试在您的申请末尾添加:

 import time

 print("Waiting to exit")
 while True:
    time.sleep(1)

...然后使用 CTRL+C 终止您的应用程序。

线程并不是编写代码 运行 并由 OS 管理的神奇方式。它们仅在您的进程中是本地的,因此如果该进程意外终止或终止,您的线程也会如此。

所以你的问题的答案是:不要使用线程,以正常方式编写你的程序,以便你可以在命令行上调用它,然后使用基于 OS 的调度程序,例如 CRON安排它。

或者,如果您的程序需要连续 运行 因为它例如建立每 5 分钟重新计算一次的缓存非常昂贵,使用进程观察器(如 supervisord)确保即使在重启或崩溃后程序继续执行。