How to schedule python script to exit at given time

旧街凉风 提交于 2021-01-27 21:52:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!