How can I run an async function using the schedule library?
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
Solution 1:
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:
import asyncio
from discord.ext import commands, tasks
from datetime import datetime, timedelta
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()
Solution 2:
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)