简体   繁体   English

如何停止/终止 python 脚本与 APScheduler 的 BackgroundScheduler() 一起运行

[英]How to stop/terminate a python script from running with BackgroundScheduler() of APScheduler

I'm trying to stop the while loop execution from inside the foo() function.我试图从 foo() function 内部停止 while 循环执行。 I've tried exit() / sys.exit without success.我试过 exit() / sys.exit 没有成功。 How can I stop completely the execution of the program from inside the function?如何从 function 内部完全停止程序的执行?

from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
import time
import sys

def foo(stop = False):
    print('Function foo executed')
    if stop: 
        sys.exit

scheduler = BackgroundScheduler() 
dd = datetime.now() + timedelta(seconds=10)
scheduler.add_job(foo, 'date', run_date=dd, args=[True])
scheduler.start()

while True:
    print('Inside the loop')
    time.sleep(2)

Use psutil使用 psutil

import psutil

psutil.Process().terminate()

From the doc, psutil.Process() If PID is omitted current process PID (os.getpid()) is used.从文档中, psutil.Process()如果省略了 PID,则使用当前进程 PID (os.getpid())。

Be aware terminate will leave with exit code 0. If you want other exit code, you can use send_signal() or even kill()请注意 terminate 将离开退出代码 0。如果您想要其他退出代码,您可以使用send_signal()甚至kill()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM