Search code examples
pythonpython-3.xpython-schedule

Use python schedule module in an efficient manner


I want to use python scheduler module for an api call.

I have two main tasks.

1-Generate token at interval of 10 mins

2-Call the api using the token generated in previous step

The expected behavior is when a user calls the api it should use the same token for 10 mins and after 10 mins the toekn will be updated in background

Here are the sample piece of code

token=""(This is a global variable)
def generate_token():
 token=//Logic to generate token//


def apicall():
 postreq=//api call using the token//


def schedule_run():
 schedule.every(10).minutes.do(get_token_api)
 while 1:
        schedule.run_pending()
        time.sleep(1)

if __name__ == "__main__":
 schedule_run()
 apicall()
 

When I am running above code the code is getting stuck in the while loop of schedule_run() and not calling apicall()

Is there any efficient way to handle this?


Solution

  • You are getting stuck in the (infinite) loop inside schedule_run. First define the two scheduled jobs, the run the schedule waiting loop:

    token=""(This is a global variable)
    def generate_token():
     token=//Logic to generate token//
    
    
    def apicall():
     schedule.run_pending() #will update the token if it has not been done in the last 10 minutes
     postreq=//api call using the token//
    
    if __name__ == "__main__":
     schedule.every(10).minutes.do(get_token_api)
     apicall()