python - 如何让 Python apscheduler 在后台运行

标签 python ps apscheduler

我想让 Python apscheduler 在后台运行,这是我的代码:

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

我刚刚得到这个:

信息:apscheduler.scheduler:调度器启动 DEBUG:apscheduler.scheduler:寻找要运行的作业 调试:apscheduler.scheduler:没有工作;等待添加作业 信息:apscheduler.scheduler:将作业“simple_task”添加到作业存储“default”

还有:

ps -e | grep python

我刚得到 54615 ttys000 0:00.00 grep python

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

最佳答案

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

尝试在您的应用程序末尾添加:

 import time

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

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

关于python - 如何让 Python apscheduler 在后台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32031667/

相关文章:

python - 如何使用 PyMorph 在 Python 中的图像中添加高斯噪声

python - 无法在 Opencv2 上导入 cv

python - Pandas :重命名具有相同名称的列

python 仅运行 apschedule BlockingScheduler 一次

python - APScheduler 选项

Pythoncard 项目集大小

python - 子进程 pid 与 ps 输出不同

linux - Linux 中的非零 CPU%

linux - 为什么我的 mac 终端的 ps -u 不工作?

python - 如何在特定时间之间以固定间隔在 python 中运行任务?