-1

I have to make request to an API to get access token. It expires in a day i.e. 86400 secs or 24 hours. I need to get a new access token once a new day is started.

Below is my API access code:

def get_access_token():
    logging.info('Started to get access token')
    response = requests.post(settings.URL, data=params).json()
    logging.info('Fetched Access token')
    return response

I need to make sure only above method get_access_token runs once at first hour everyday. My whole job runs every hour using blockingscheduler. Only above piece of code needs to run once at first hour everyday.

Please let me know how it can be achieved ?

Shankar Guru
  • 1,071
  • 2
  • 26
  • 46
  • 2
    You should read cron documentation to understand how to made something like this. Check cron tag at https://stackoverflow.com/tags/cron/info – tanaydin Aug 20 '18 at 07:58
  • 2
    Possible duplicate of [What is the best way to repeatedly execute a function every x seconds in Python?](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python) – bergerg Aug 20 '18 at 07:59
  • Are you using a web framework like Flask or Django? – Jundiaius Aug 20 '18 at 09:09

2 Answers2

1

You can use an infinite loop for this, with some smart sleeping step:

import time
starttime=time.time()
interval=86400 
while True:
  get_access_token()
  time.sleep(interval - ((time.time() - starttime) % interval))

If you want the program to run at the first hour, just make sure you run it the first time at such hour.

ibarrond
  • 6,617
  • 4
  • 26
  • 45
1

If you are working in a Linux environment, cron would help you achieve this.

  1. Get your code to be executed in a script.py
  2. Execute crontab -e in the terminal
  3. Set up a new line such as:

    0 9 * * * python /path/to/your/script/script.py >/dev/null 2>&1
    

That will execute your script every day at 9:00 am.

Pablo M
  • 326
  • 2
  • 7