From e6f7e52d980d029e273551ab004e615061d4eca6 Mon Sep 17 00:00:00 2001 From: Lonami Date: Wed, 31 Jul 2019 13:10:34 +0200 Subject: [PATCH] Created Scheduling Functions (markdown) --- Scheduling-Functions.md | 43 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Scheduling-Functions.md diff --git a/Scheduling-Functions.md b/Scheduling-Functions.md new file mode 100644 index 0000000..a76b199 --- /dev/null +++ b/Scheduling-Functions.md @@ -0,0 +1,43 @@ +Telethon doesn't come with scheduling builtin because it would be unnecessary bloat. If you don't want more dependencies, you can just use `asyncio` to schedule functions to run later or at a given time. + +For example, if you want to run `foo` after 10 minutes: + +```python +async def foo(): + print('hi') + +def foo_cb(): + client.loop.create_task(foo()) + +client.loop.call_later(10 * 60, foo_cb) +``` + +[`loop.call_later()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_later) can only schedule synchronous functions (`call_cb`), but you can use `create_task` to spawn a background, asynchronous task. + +You can also run something "every N seconds". For example, to repeat `foo` every 10 minutes: + +```python +async def foo(): + print('hi') + +def foo_cb(): + client.loop.create_task(foo()) + client.loop.call_later(10 * 60, foo_cb) + +foo_cb() +``` + +This schedules itself again when it runs, so it is always running. It runs, 10 minutes pass, it schedules itself again, and repeat. This is similar to JavaScript's `setTimeout`. + +You can also use `while` loops: + +```python +async def foo(): + while True: + print('hi') + await sleep(10 * 60) + +client.loop.create_task(foo()) +``` + +If you don't mind using other libraries, [`aiocron`](https://github.com/gawel/aiocron) is a good option. See https://crontab.guru/ to learn its time syntax. \ No newline at end of file