Search code examples
pythonpython-3.xwhile-loopscheduled-tasksthread-synchronization

How to properly schedule while function to be interrupted and another function called


I have a script that runs pretty much 24/7. I would like it to be properly interrupted several times a day.

from time import sleep

def function_one():
    while True:
        print("I'm working 24/7 and doing some important stuff here!")
        print("Very important!")
        sleep(5)

def function_two():
    print("I just need to do my job once, however, function_one should be stopped while i'm working!")    

I want function_one to be interrupted (in between loops) every 3 hours then function_two to be called once and right after that function_one should continue working.

What is the proper way of doing this?


Solution

  • Why not put the call to function 2 within function 1 itself. That way it'll wait until function 2 has run to resume function 1. Something like this:

    from __future__ import generators
    from time import sleep
    import time
    
    def function_one():
        while True:
            print("I'm working 24/7 and doing some important stuff here!")
            print("Very important!")
            #First bit checks whether the hour is divisible by 3 (every 3 hours)
                                                    #This bit checks that the minute and seconds combined are the first 5 seconds of the hour
            if int(time.strftime("%H"))%3 == 0 and int(time.strftime("%M%S")) < 6:
                #Calls function 2 and won't resume until function 2 is finished
                function_two()
                print("That was the 2 second wait from function 2")
            sleep(5)
    
    def function_two():
        print("I just need to do my job once, however, function_one should be stopped while i'm working!")
        sleep(2)
    
    function_one()
    

    Hopefully this works for what you want.