Access Token Expiry Handling in Batch Processing Scripts

We are encountering intermittent failures in our nightly data synchronization jobs. The script retrieves a JWT access token at the start of the execution window. The batch process iterates through approximately five thousand queue configurations to update specific attributes via the Genesys Cloud API. The job fails midway through the list with a 401 Unauthorized error. The token has a standard lifespan of thirty-six hundred seconds. The total execution time for the batch exceeds this window.

The current implementation fetches the token once using the client credentials grant type. It stores the token in a session variable. Subsequent API calls reuse this same token. There is no refresh logic implemented within the loop. The error payload confirms the token is expired. We need to implement a mechanism to detect the expiry and refresh the token automatically without restarting the entire job.

Here is the simplified Python logic we are using:

import requests

def get_token(client_id, client_secret):
 url = "https://api.mypurecloud.com/oauth/token"
 headers = {"Content-Type": "application/x-www-form-urlencoded"}
 data = {
 "grant_type": "client_credentials",
 "client_id": client_id,
 "client_secret": client_secret
 }
 response = requests.post(url, headers=headers, data=data)
 return response.json()["access_token"]

def update_queue(token, queue_id, settings):
 url = f"https://api.mypurecloud.com/api/v2/queues/{queue_id}"
 headers = {
 "Authorization": f"Bearer {token}",
 "Content-Type": "application/json"
 }
 response = requests.put(url, headers=headers, json=settings)
 if response.status_code == 401:
 # Need to handle refresh here
 pass
 return response

# Main execution
token = get_token("my_client_id", "my_client_secret")
for queue_id in queue_list:
 update_queue(token, queue_id, new_settings)

The documentation mentions using the refresh token, but the client credentials grant does not return one. We are unsure if we should request a new token on every 401 error or implement a proactive refresh based on the expiry timestamp in the JWT payload. Parsing the JWT to check the exp claim seems like the cleaner approach. How are others handling this in their automation scripts? We want to avoid the overhead of making a new request for every single queue update if possible.