'Change interval of schedule in python while script keeps running

I am trying to use the schedule function in python. Works pretty well, but I want to change the interval while the python script keeps running. The interval variable is read from sql database.

But it doesn't seemed to work. Maybe you could take a quick look. At start the interval was set to 1 minute. After first execution I changed the interval to 720 minutes.

The script recognized it and i was expecting, that the old schedule job were canceled and a new job were started with new interval. But this didn't happend...

# Just do this once:
sql_connect()
# from sql :  interval = 1
schedule.every(interval).minutes.do(send_routine)
old_interval = interval

while 1:
    sql_connect()
    if interval != old_interval:
        print("Interval has changed! Setting new interval to " + str(interval) + " Minutes...")
        old_interval = interval
        schedule.clear()
        time.sleep(0.2)
        print("Starting new job with new interval...")
        schedule.every(interval).minutes.do(send_routine)

    n = schedule.idle_seconds()
    print("Seconds to next Routine: " + str(n))
    
    if n is None:
        # no more jobs
        break
    elif n > 0:
        print("Going to sleep until next time...")
        # sleep exactly the right amount of time
        time.sleep(n)
    print("Sending next Routine....")
    schedule.run_pending()

Output looks like this:

Seconds to next Routine: 59.737961
Going to sleep until next time...
Sending next Routine....
Mail Routine...
Interval has changed! Setting new interval to 720 Minutes...
Starting new job with new interval...
Seconds to next Routine: -0.00844
Sending next Routine....
Mail Routine...
Seconds to next Routine: 59.966664
Going to sleep until next time...
Sending next Routine....
Mail Routine...
Seconds to next Routine: 59.442492
Going to sleep until next time...
Sending next Routine....
Mail Routine...
Seconds to next Routine: 0.292306
Going to sleep until next time...
Sending next Routine....
Mail Routine...
Seconds to next Routine: 59.971122


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source