mirror of
https://github.com/LonamiWebs/Telethon.git
synced 2024-11-22 01:16:35 +03:00
Created Scheduling Functions (markdown)
parent
2f30522020
commit
e6f7e52d98
43
Scheduling-Functions.md
Normal file
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.
|
Loading…
Reference in New Issue
Block a user