简体   繁体   English

Python,类中的函数,每n秒触发一次

[英]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. 我正在使用python 2.7.x,并且有一个类是使用JSON API的python库。 To use the services that the REST API allows, a person must pass a user name and password to generate a token. 要使用REST API允许的服务,一个人必须传递用户名和密码来生成令牌。 These are short lived tokens 5-60 seconds long. 这些是短暂的令牌,持续时间为5-60秒。 How could I modify an existing class to create a function that runs every n number of seconds to automatically refresh the token? 我如何修改现有的类以创建每n秒运行一次以自动刷新令牌的函数?

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. 因此,在此示例中,我希望每10秒触发一次generate_token。 This should ensure that the token used is always fresh for the life of the object MyClass. 这应确保所使用的令牌在对象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. 60通知,线程配置为每60秒运行一次。

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. 尽管确实来自Lukas Graf的评论可能是一种更好的方法,但是请尝试使用您当前的令牌进行请求,并在请求失败时生成一个新令牌。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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