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

后端 未结 5 944
广开言路
广开言路 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: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)
    
        ...
    
    

提交回复
热议问题