如何使用计划库运行异步功能? [英] How can I run an async function using the schedule library?

查看:88
本文介绍了如何使用计划库运行异步功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用discord.py rewrite编写一个discord机器人,我想每天在特定时间运行一个函数.我完全没有异步函数的经验,我不知道如何在不使用等待"的情况下运行一个异步函数.这只是我的代码的一部分,这就是为什么有些事情可能无法定义的原因.

I'm writing a discord bot using discord.py rewrite, and I want to run a function every day at a certain time. I'm not experienced with async functions at all and I can't figure out how to run one without using "await." This is only a piece of my code which is why some things may not be defined.

async def send_channel():
    try:
        await active_channel.send('daily text here')
    except Exception:
        active_channel_id = None
        active_channel = None

async def timer():
    while True:
        schedule.run_pending()
        await asyncio.sleep(3)
        schedule.every().day.at("21:57").do(await send_channel())

@bot.event
async def on_ready():
    print("Logged in as")
    print(bot.user.name)
    print(bot.user.id)
    print("------")

    bot.loop.create_task(timer())

使用schedule.every().day.at("00:00").do()函数,将await send_channel()放在.do()的参数中时出现此错误:

Using the schedule.every().day.at("00:00").do() function, I get this error when I put await send_channel() in the paramaters of .do():

self.job_func = functools.partial(job_func,* args,** kwargs) TypeError:第一个参数必须是可调用的

self.job_func = functools.partial(job_func, *args, **kwargs) TypeError: the first argument must be callable

但是当我不使用await且仅将send_channel()作为参数时,会出现此错误:

But when I don't use await, and I just have send_channel() as parameters, I get this error:

RuntimeWarning:从未等待协程'send_channel'

RuntimeWarning: coroutine 'send_channel' was never awaited

我不是很擅长编程,所以如果有人可以尝试为我愚弄它,那将是很棒的事情.

I'm not super good at programming so if someone could try to dumb it down for me that would be awesome.

谢谢

推荐答案

这是一个老问题,但是我最近遇到了同样的问题.您可以使用 run_coroutine_threadsafe 来安排协程进入事件循环(而不是回调):

This is an old question, but I recently ran into the same issue. You can use run_coroutine_threadsafe to schedule a coroutine to the event loop (rather than a callback):

asyncio.run_coroutine_threadsafe(async_function(), bot.loop)

这篇关于如何使用计划库运行异步功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆