【问题标题】:How to schedule an async function in python? [duplicate]如何在 python 中调度异步函数? [复制]
【发布时间】:2020-06-07 11:45:55
【问题描述】:

我正在为不和谐制作一个机器人。和这个问题基本一样:How can I run an async function using the schedule library?

除了上面的链接没有任何效果。就我而言,我得到“从未等待过我的功能”

async def birthday():        
    channel = client.get_channel(xxxxxx)
    fileName = open("birthdayFile.txt", "r")
    today = time.strftime('%m%d')

    for line in fileName:
            if today in line:
                    line = line.split(' ')

                    line[-1] = line[-1].strip()
                    if line[-1] != line[1]:
                            bdayperson = line[1]+' '+line[2]
                    else:
                            bdayperson = line[1]

                    await channel.send(f"Happy Birthday to "+ bdayperson + "! ????????" )


schedule.every().day.at("18:36").do(client.loop.call_soon_threadsafe, birthday)

【问题讨论】:

  • 您能否显示您尝试遵循other question 答案中的建议的代码?正如您自己指出的那样,这个问题是重复的,但也许可以改进另一个问题的答案,以更清楚地展示如何解决问题。

标签: python-3.x bots discord python-asyncio discord.py


【解决方案1】:

你的生日方法是一个异步方法,也称为协程。这与“正常”/非异步方法不同。

您使用的调度库仅适用于非异步方法。您必须将生日异步方法包装在普通方法中。您的计划库可以调用普通方法。

但是,为了使 discord.py 库能够运行,它需要一个正在运行的事件循环。然而,调度库是一种阻塞方法。它有自己的内部逻辑并阻止其他脚本执行。这意味着您不能将 schedule 模块与 discord 模块一起使用。

您需要找到一个内置异步支持的库或编写自己的调度逻辑。

您可以通过使用另一个 Stackoverflow 问题中链接的不同线程来解决阻塞问题:How can I run an async function using the schedule library?
你还没有关注。

总的来说,这是一种非常老套的方法,我建议您编写自己的调度逻辑。 schedule 模块不能很好地与 discord 模块配合使用。

【讨论】:

  • 不幸的是,该链接中的解决方案不适用于我和该问题的 OP...我找到了一个名为“aioschedule”的库,它似乎是异步调度程序并且应该是非阻塞的。我会尝试解决。谢谢!
猜你喜欢
  • 2021-12-25
  • 2020-03-09
  • 2021-03-07
  • 2021-07-31
  • 2020-12-20
  • 1970-01-01
  • 2016-01-14
相关资源
最近更新 更多