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

Viewed 293

I'm trying to stop the while loop execution from inside the foo() function. I've tried exit() / sys.exit without success. How can I stop completely the execution of the program from inside the 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)
1 Answers

Use psutil

import psutil

psutil.Process().terminate()

From the doc, psutil.Process() If PID is omitted current process PID (os.getpid()) is used.

Be aware terminate will leave with exit code 0. If you want other exit code, you can use send_signal() or even kill()

Related