我正在做一个项目。 以下是问题所在的文件。
cli.py
import click
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler(daemon=True)
def func():
print("scheduler running with interval....")
@click.command()
@click.option('--interval', type=int, default=5, help='Interval for the scheduler in minutes')
def start_scheduler(interval):
scheduler.add_job(func, 'interval', seconds=interval)
scheduler.start()
try:
# Keep the script running (use Ctrl+C to stop it)
while True:
pass
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()
@click.command()
def stop_scheduler():
if scheduler.running:
scheduler.shutdown()
print("scheduler shut down")
else:
print("scheduler is not running")
@click.command()
def status_scheduler():
if scheduler.running:
print("Scheduler is running.")
else:
print("Scheduler is not running.")
设置.py
""" This file is used for packaging the source code and command line interface"""
from setuptools import setup
setup(
name='test_package',
version='0.1.0',
packages=['my_pack'],
install_requires=['click','APScheduler'],
entry_points={
'console_scripts': [
'start = my_pack.cli:start_scheduler'
'status = my_pack.cli:status_scheduler',
'stop = my_pack.cli:stop_scheduler',
],
},
)
我得到的输出:
当我在终端上运行
start
命令时,它不会在后台运行。
要退出脚本,需要点击 ctl+C
我在 Ubuntu 中使用虚拟环境。
预期输出:
当我发出启动命令时,它应该返回 shell 来输入另一个命令,并且应该在后台运行,直到手动停止。
$ start
$
Python版本:Python 3.10.12
平台:#40~22.04.1-Ubuntu
您可能应该将其制作成systemd 单元。除了允许您在系统启动时启动它之外,您还可以随意启动和停止调度程序进程(分别使用
systemctl start myservice
或 systemctl stop myservice
)。
一种替代方案是使用 systemd 计时器,如果您只想每分钟运行一个 Python 脚本并且它没有太多启动开销。那么你也不需要 APScheduler。