我想让 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/