简体   繁体   中英

Python, Function in Class that fires off every n seconds

I am using python 2.7.x, and I have a class that is a python libraries to use a JSON API. To use the services that the REST API allows, a person must pass a user name and password to generate a token. These are short lived tokens 5-60 seconds long. How could I modify an existing class to create a function that runs every n number of seconds to automatically refresh the token?

Example Class:

class MyClass(object):
   _token = None
   def __init__(self, username, password):
      self._username = username
      self.password = password
      self._token = self.generate_token()
   def generate_token(username, password):
      # do some stuff to get token
      self._token = "token value"

So in this example, I'd like generate_token to be fired off every 10 seconds. This should ensure that the token used is always fresh for the life of the object MyClass.

Thank you

You can use threading:

import time, threading
def generate_token(username, password):
      # do some stuff to get token
      self._token = "token value"
      threading.Timer(60, generate_token(username, password)).start()

60 informs that, thread configures to run every 60 seconds.

I think something like the following should work, using a thread to generate the token in a loop:

import time
import threading

class MyClass(object):
   _token = None
   def __init__(self, username, password):
      self._username = username
      self.password = password
      self._token = self.generate_token()
      self._thread = threading.Thread(target=self.token_loop)
      self._thread.start()
   def generate_token(username, password):
      # do some stuff to get token
      self._token = "token value"
   def token_loop(self):
      while True:
         time.sleep(10)
         self.generate_token()

You may want to add some locking around generating and using the token if you think race conditions might be an issue (like the token being regenerated while you are trying to use it resulting in an inconsistent or invalid token).

Although really the comment from Lukas Graf is probably a better approach, try to do a request with your current token and generate a new one when the request fails.

You could pass through a generator before getting a token, and update the token if a certain time has passed:

import time

def token_generator(refresh_rate=10):
    token = self.get_token(self.username, self.password)
    t0 = time.clock()
    while True:
        if time.clock() - t0 <= refresh_rate:
            token = self.get_token(self.username, self.password)
            t0 = time.clock()
        yield token

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM