[英]Python: How can I delete a variable after being unused for X minutes?
I have the following code:我有以下代码:
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)
I want to run a function clear_data(big_var)
if the last use of big_var
was X minutes ago, in order to save memory.如果上次使用big_var
是 X 分钟前,我想运行 function clear_data(big_var)
,以保存 memory。
I tried:我试过了:
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)
But this prevents the function func1()
from finishing and the max_concurrency
decorator will only allow 1 instance of func1()
to be running at a time.但这会阻止 function func1()
完成,并且max_concurrency
装饰器一次只允许func1()
的 1 个实例运行。
How can I resolve this issue?我该如何解决这个问题?
EDIT: Rewrote question to make it more clear编辑:重写问题以使其更清楚
threading.Timer is a function that calls the second argument after the first argument number of seconds. threading.Timer是一个 function 在第一个参数秒数之后调用第二个参数。 You might do something like:您可能会执行以下操作:
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)
It does not block either.它也不阻塞。
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()
The above will produce以上会产生
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.