问题
I need to schedule a python script which can exit and kill it self at a given time. For scheduling, I am using python schedule and below is the code:
import schedule
from threading import Thread
import time
import sys
def exit_data():
print("Exiting")
sys.exit()
def exit_data_thread():
schedule.every().day.at('13:20').do(exit_data)
while True:
schedule.run_pending()
time.sleep(1)
def main():
Thread(target=exit_data_thread).start()
while True:
time.sleep(1)
main()
Function exit_data() runs at given time and it prints Exiting but do not exit. It only prints Exiting and then it keeps running. I have also used quit instead of sys.exit(). Please help. Thanks
回答1:
Try to send signal to yourself :p
import schedule
from threading import Thread
import time
import sys
import os
import signal
def exit_data():
print("Exiting")
# sys.exit()
os.kill(os.getpid(), signal.SIGTERM)
def exit_data_thread():
schedule.every(3).seconds.do(exit_data)
while True:
schedule.run_pending()
time.sleep(1)
def main():
Thread(target=exit_data_thread).start()
while True:
time.sleep(1)
main()
回答2:
To close the entire program within a thread, you can use os._exit(). Calling sys.exit() will only exit the thread, not the entire program.
来源:https://stackoverflow.com/questions/53424532/how-to-schedule-python-script-to-exit-at-given-time