Skip to content

Scheduling Functions

Lonami edited this page Jul 31, 2019 · 11 revisions

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:

async def foo():
    print('hi')

def foo_cb():
    client.loop.create_task(foo())

client.loop.call_later(10 * 60, foo_cb)

loop.call_later() can only schedule synchronous functions (foo_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:

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.

Important note. Do not call the synchronous function when you schedule it, or it will recurse forever. loop.call_later(delay, func()) won't work, but loop.call_later(delay, func) will.

You can also use while loops:

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 is a good option. See https://crontab.guru/ to learn its time syntax.