2

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

S Andrew
  • 5,592
  • 27
  • 115
  • 237

2 Answers2

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()
supl
  • 114
  • 5
1

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.

Unsolved Cypher
  • 1,025
  • 10
  • 24