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

后端 未结 5 936
广开言路
广开言路 2020-11-29 10:52

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

相关标签:
5条回答
  • 2020-11-29 11:06

    Another option is to use apscheduler's AsyncIOScheduler, which works more naturally with async functions (such as send_channel). In your case, you can simply write something of the form:

    scheduler = AsyncIOScheduler()
    scheduler.add_job(send_channel, trigger=tr)
    scheduler.start()
    

    Where tr is a trigger object. You can use either IntervalTrigger with a 1-day interval and a start date at 21:57, or a CronTrigger.

    Note that at the end of your program it is recommended to call shutdown() on the scheduler object.

    0 讨论(0)
  • 2020-11-29 11:11

    The built-in solution to this in discord.py is to use the discord.ext.tasks extension. This lets you register a task to be called repeatedly at a specific interval. When the bots start, we'll delay the start of the loop until the target time, then run the task every 24 hours:

    from discord.ext import commands, tasks
    from datetime import datetime, timdelta
    
    bot = commands.Bot("!")
    
    @tasks.loop(hours=24)
    async def my_task():
        ...
    
    @my_task.before_loop
    async def before_my_task():
        hour = 21
        minute = 57
        await bot.wait_until_ready()
        now = datetime.now()
        future = datetime.datetime(now.year, now.month, now.day, hour, minute)
        if now.hour >= hour and now.minute > minute:
            future += timedelta(days=1)
        await asyncio.sleep((future-now).seconds)
    
    my_task.start()
    
    0 讨论(0)
  • 2020-11-29 11:13

    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)
    
    0 讨论(0)
  • 2020-11-29 11:13

    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)
    
    0 讨论(0)
  • 2020-11-29 11:33

    Going through the very same problem I found a solution that mixes some of the previous solutions:

    import schedule
    from discord.ext import tasks
    
    @tasks.loop(hours=24)
    async def send_channel():
        pass
    

    and later just before the main thread I define

    def event_starter(func):
        if not func.is_running():
            func.start()
    
    schedstop = threading.Event()
    def timer():
        while not schedstop.is_set():
            schedule.run_pending()
            sleep(1)
    schedthread = threading.Thread(target=timer)
    schedthread.start()
    

    and finally, in the main thread:

    if __name__ == "__main__":
    
        ...
    
        schedule.every().day.at('21:57:00').do(event_starter, send_channel)
    
        ...
    
    
    0 讨论(0)
提交回复
热议问题