Created Scheduling Functions (markdown)

Lonami 2019-07-31 13:10:34 +02:00
parent 2f30522020
commit e6f7e52d98

43
Scheduling-Functions.md Normal file

@ -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.