I'm trying to extend a solution so that the Pyton program ends after schedule is done working for a time period.
I am following the solution https://stackoverflow.com/questions/52198116/how-to-schedule-job-with-a-particular-time-as-well-as-interval?rq=3
and I pasted the code for the specific solution I'm using here:
import schedule
import time
from datetime import datetime as dt
def job():
now = dt.now()
dt_string = now.strftime('%Y-%m-%d %H:%M:%S')
print ("I am working " ,dt_string )#your job function
def schedule_every_four_hours():
job() #for the first job to run
schedule.every(2).minutes.until("09:46").do(job)
print(' 2 Minuten')
return schedule.CancelJob
schedule.every().day.at("09:29").do(schedule_every_four_hours)
while True:
schedule.run_pending()
time.sleep(1)
The problem is that this will never exit. If I comment out the "while True", then it will exit, but scheduling code will never run because the program does exit. So how does write the code so that after running for a period of time the python program actually exits and cleans up nicely by itself. My intent is to add code that writes data to a file, so I want to be able to flush buffers and close the file cleanly as well as return a return code.
There is another related question where it's recommended to use
os.kill(os.getpid(), signal.SIGTERM)
But to me this seems to be an unclean programming way to end a program. See: https://stackoverflow.com/questions/53424532/how-to-schedule-python-script-to-exit-at-given-time