|
| 1 | +Scheduling Tasks |
| 2 | +================ |
| 3 | + |
| 4 | +Scheduling tasks means executing one or more functions periodically at pre-defined intervals or after a delay. This is |
| 5 | +useful, for example, to send recurring messages to specific chats or users. |
| 6 | + |
| 7 | +Since there's no built-in task scheduler in Pyrogram, this page will only show examples on how to integrate Pyrogram |
| 8 | +with the main Python schedule libraries such as ``schedule`` and ``apscheduler``. For more detailed information, you can |
| 9 | +visit and learn from each library documentation. |
| 10 | + |
| 11 | +Using ``schedule`` |
| 12 | +------------------ |
| 13 | + |
| 14 | +- Install with ``pip3 install schedule`` |
| 15 | +- Documentation: https://schedule.readthedocs.io |
| 16 | + |
| 17 | +.. code-block:: python |
| 18 | +
|
| 19 | + import time |
| 20 | +
|
| 21 | + import schedule |
| 22 | +
|
| 23 | + from pyrogram import Client |
| 24 | +
|
| 25 | + app = Client("my_account") |
| 26 | +
|
| 27 | +
|
| 28 | + def job(): |
| 29 | + app.send_message("me", "Hi!") |
| 30 | +
|
| 31 | +
|
| 32 | + schedule.every(3).seconds.do(job) |
| 33 | +
|
| 34 | + with app: |
| 35 | + while True: |
| 36 | + schedule.run_pending() |
| 37 | + time.sleep(1) |
| 38 | +
|
| 39 | +
|
| 40 | +
|
| 41 | +Using ``apscheduler`` |
| 42 | +--------------------- |
| 43 | + |
| 44 | +- Install with ``pip3 install apscheduler`` |
| 45 | +- Documentation: https://apscheduler.readthedocs.io |
| 46 | + |
| 47 | +.. code-block:: python |
| 48 | +
|
| 49 | + from apscheduler.schedulers.background import BackgroundScheduler |
| 50 | +
|
| 51 | + from pyrogram import Client |
| 52 | +
|
| 53 | + app = Client("my_account") |
| 54 | +
|
| 55 | +
|
| 56 | + def job(): |
| 57 | + app.send_message("me", "Hi!") |
| 58 | +
|
| 59 | +
|
| 60 | + scheduler = BackgroundScheduler() |
| 61 | + scheduler.add_job(job, "interval", seconds=3) |
| 62 | +
|
| 63 | + scheduler.start() |
| 64 | + app.run() |
| 65 | +
|
| 66 | +``apscheduler`` does also support async code, here's an example with |
| 67 | +`Pyrogram Asyncio <https://docs.pyrogram.org/intro/install.html#asynchronous>`_: |
| 68 | + |
| 69 | +.. code-block:: python |
| 70 | +
|
| 71 | + from apscheduler.schedulers.asyncio import AsyncIOScheduler |
| 72 | +
|
| 73 | + from pyrogram import Client |
| 74 | +
|
| 75 | + app = Client("my_account") |
| 76 | +
|
| 77 | +
|
| 78 | + async def job(): |
| 79 | + await app.send_message("me", "Hi!") |
| 80 | +
|
| 81 | +
|
| 82 | + scheduler = AsyncIOScheduler() |
| 83 | + scheduler.add_job(job, "interval", seconds=3) |
| 84 | +
|
| 85 | + scheduler.start() |
| 86 | + app.run() |
| 87 | +
|
0 commit comments