0

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?

Hannah
  • 163
  • 2
  • 12

1 Answers1

0

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()
Learning is a mess
  • 7,479
  • 7
  • 35
  • 71
  • I can not use the api call in a loop. The expected behavior is when a user calls the api it should use the same token for 10 mins and after 10 mins the token will be updated in background – Hannah Jun 02 '23 at 10:30
  • Okay I think I get what you want, let's move the schedule checkup inside the api_call function then. Note that this solution does not necessarily scale trivially (readable) if you have more items (especially if they are coroutines or computationally intensive) on the schedule. – Learning is a mess Jun 02 '23 at 10:42