python - 如何使全局变量从数据库中刷新

标签 python python-2.7

<分区>

我有一个永远运行的程序(虽然是 True),没关系,但我需要在内部使用代表表中用户数量的数字(没有必要精确,所以我想避免 COUNT(* ) 每当我需要那个数字时查询数据库,但问题是当它在实数和那个数字之间有很大的误差时)。我想让我的号码每天都刷新。如何制作像全局变量一样刷新自身但不会永远运行(刷新时不使用任何 CPU 时间)?

最佳答案

使用类属性,仅在经过一段时间后才再次访问服务器。

from datetime import datetime, timedelta
import random

class MyThing(object):

    def __init__(self, refresh_interval=60*60*24):
        self.refresh_interval = refresh_interval
        self._n_users = None
        self._last_refresh = datetime.now() - timedelta(0, refresh_interval)
        # setup db connection stuff

    @property
    def n_users(self):
        if (datetime.now() - self._last_refresh).total_seconds() > self.refresh_interval:
            self._n_users = self.fetch_from_db()
            self._last_refresh = datetime.now()
        return self._n_users

    def fetch_from_db(self):
        # TODO
        return random.randint(0, 100)

t = MyThing(refresh_interval=3)
print t.n_users

关于python - 如何使全局变量从数据库中刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21168904/

相关文章:

python - Django 南 : Migrating FK from another table

python-2.7 - HTTPException:URL 的 SSL 证书无效和/或丢失:https://accounts.google.com/o/oauth2/token

Python 2.7 创建多维列表

javascript - 从javascript获取python函数的值

python - 使用 Beautiful Soup 从非类部分获取数据

python - Python 中的 random.randint(1,n)

python - 用 python 分割数据框

python - 堆叠矩阵的最佳方式

python - 递归树遍历并将每个输出作为字符串python返回

Python:导入错误:/usr/local/lib/python2.7/lib-dynload/_io.so: undefined symbol :PyUnicodeUCS2_Replace