How can I run an async function using the schedule library?

大憨熊 提交于 2020-01-21 09:10:15

问题


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())

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: the first argument must be callable

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

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.

Thanks


回答1:


What you're doing doesn't work because do takes a function (or another callable), but you're trying to await or call a function, and then pass it the result.

await send_channel() blocks until the send finishes and then gives you None, which isn't a function. send_channel() returns a coroutine that you can await later to do some work, and that isn't a function either.

If you passed it just send_channel, well, that is a function, but it's an ascynio coroutine function, which schedule won't know how to run.


Also, rather than trying to integrate schedule into the asyncio event loop, and figure out how to wrap async jobs up as schedule tasks and vice versa and so on, it would far easier to just give schedule its own thread.

There's a FAQ entry on this:

How to continuously run the scheduler without blocking the main thread?

Run the scheduler in a separate thread. Mrwhick wrote up a nice solution in to this problem here (look for run_continuously()).

The basic idea is simple. Change your timer function to this:

schedstop = threading.Event()
def timer():
    while not schedstop.is_set():
        schedule.run_pending()
        time.sleep(3)
schedthread = threading.Thread(target=timer)
schedthread.start()

Do this at the start of your program, before you even start your asyncio event loop.

At exit time, to stop the scheduler thread:

schedstop.set()

Now, to add a task, it doesn't matter whether you're in your top-level code, or in an async coroutine, or in a scheduler task, you just add it like this:

schedule.every().day.at("21:57").do(task)

Now, back to your first problem. The task you want to run isn't a normal function, it's an asyncio coroutine, which has to be run on the main thread as part of the main event loop.

But that's exactly what call_soon_threadsafe is for. What you want to call is:

bot.loop.call_soon_threadsafe(send_channel)

To ask scheduler to run that, you just pass bot.loop.call_soon_threadsafe as the function and send_channel as the argument.

So, putting it all together:

schedule.every().day.at("21:57").do(
    bot.loop.call_soon_threadsafe, send_channel)



回答2:


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)


来源:https://stackoverflow.com/questions/51530012/how-can-i-run-an-async-function-using-the-schedule-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!