等待线程函数

2024-07-04 05:33:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了一个函数,该函数设置为每小时向一个不协调的通道发送一条消息。这将与典型的on_message()命令一起运行,因此我考虑使用线程将reccuring函数放在线程内。你知道吗

我试着像你一样异步/等待线程,但是没有成功。我怎样才能使它成为可能,这样我就可以有一个消息重复每小时伴随着典型的命令?你知道吗

我的代码如下

async def reccur_func():
    while 1:
        await reccurship()
        time.sleep(30)

client = discord.Client()

threading.Thread(target = reccur_func).start()   #I tried putting await and async at the beginning of this line

@client.event
async def on_message(ctx):

    ......

client.run('....')

谢谢大家


Tags: 函数命令client消息messageasync定义on
3条回答

看起来你可能把AsyncIO和线程技术混为一谈了。你知道吗

如果要使用AsyncIO,则需要将reccur_func()的任务添加到事件循环中。This other question将提供更多细节。你知道吗

如果要使用线程,请从reccur_func()中删除await

def reccur_func():
    while 1:
        # Do something
        time.sleep(30)

您可以找到有关线程in this question的更多信息。你知道吗

实现这一点的方法是使用discord.ext.tasks扩展将reccurship转换为task

from discord.ext import tasks, commands

bot = commands.Bot("!")

@bot.event
async def on_message(message):
    ...

@tasks.loop(hours=1)
async def reccurship():
    ...

@reccurship.before_loop
async def before_reccurship():
    await bot.wait_until_ready()

recurrship.start()

bot.run("token")

这并不是一个确切的问题的答案,但在我的情况下是有效的。你知道吗

在discord中,我使用了client.loop.create_task(reccur_func()),它执行了这个函数(它自己重复),同时继续运行其他所有的函数。你知道吗

相关问题 更多 >

    热门问题