【问题标题】:Python: How can I delete a variable after being unused for X minutes?Python:如何在未使用 X 分钟后删除变量?
【发布时间】:2020-05-04 10:46:01
【问题描述】:

我有以下代码:

from discord.ext import commands

bot = commands.Bot(command_prefix= prefix)
big_var = {}

@bot.command(name='func1')
@commands.max_concurrency(1, wait = True)
async def func1(ctx):
    func1code(big_var)

bot.run(TOKEN)

如果上次使用 big_var 是 X 分钟前,我想运行函数 clear_data(big_var),以节省内存。

我试过了:

from discord.ext import commands

bot = commands.Bot(command_prefix= prefix)
big_var = {}

@bot.command(name='func1')
@commands.max_concurrency(1, wait = True)
async def func1(ctx):
    func1code(big_var)
    await asyncio.sleep(600)
    clear_data(big_var)

bot.run(TOKEN)

但这会阻止函数func1() 完成,并且max_concurrencydecorator 将只允许一次运行func1() 的1 个实例。

我该如何解决这个问题?

编辑:重写问题以使其更清晰

【问题讨论】:

  • 这似乎有点宽泛,并且是已经有可用信息的主题。你能说得更具体点吗?
  • 您要求的是缓存的标准用例,即如果生存时间已过,则删除对象。 Python内置了lru_cache,但不确定是否支持TTL。
  • Here 和 here 是在 Python 中实现这种模式的一些想法。

标签: python


【解决方案1】:

threading.Timer 是一个在第一个参数秒数之后调用第二个参数的函数。你可能会这样做:

def del_big_var():
    global big_var
    del big_var

t = threading.Timer(X * 60, del_big_var)

def command_that_need_big_var():
    global t
    t.cancel()
    t = threading.Timer(X * 60, del_big_var)

它也不阻塞。

import threading
import time

def foo(*args, **kwargs):
    print("TIME!")

def main():
    t = threading.Timer(3, foo)
    t.start()
    while True:
        print("going")
        time.sleep(1)

main()

上面会产生

going
going
going
TIME!
going
going
going
Traceback (most recent call last):
  File "thread_timer.py", line 15, in <module>
    main()
  File "thread_timer.py", line 13, in main
    time.sleep(1)
KeyboardInterrupt

【讨论】:

  • 在查看 threading.Timer 时,我找不到它是否会阻止我的功能继续,在这种情况下问题仍然存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
相关资源
最近更新 更多