|
| 1 | +import asyncio |
| 2 | +import datetime |
| 3 | + |
| 4 | +from taskiq_redis import ListQueueBroker |
| 5 | + |
| 6 | +from taskiq import TaskiqScheduler |
| 7 | +from taskiq.api import run_receiver_task, run_scheduler_task |
| 8 | +from taskiq.schedule_sources import LabelScheduleSource |
| 9 | + |
| 10 | + |
| 11 | +async def main() -> None: |
| 12 | + # Here we define a broker. |
| 13 | + dyn_broker = ListQueueBroker("redis://localhost") |
| 14 | + dyn_scheduler = TaskiqScheduler(dyn_broker, [LabelScheduleSource(dyn_broker)]) |
| 15 | + |
| 16 | + await dyn_broker.startup() |
| 17 | + |
| 18 | + # Now we register lambda as a task. |
| 19 | + dyn_task = dyn_broker.register_task( |
| 20 | + lambda x: print("A", x), |
| 21 | + task_name="dyn_task", |
| 22 | + # We add a schedule when to run task. |
| 23 | + schedule=[ |
| 24 | + { |
| 25 | + # Here we also can specify cron instead of time. |
| 26 | + "time": datetime.datetime.utcnow() + datetime.timedelta(seconds=2), |
| 27 | + "args": [22], |
| 28 | + }, |
| 29 | + ], |
| 30 | + ) |
| 31 | + |
| 32 | + # We create scheduler after the task declaration, |
| 33 | + # so we don't have to wait a minute before it gets to the task. |
| 34 | + # However, defining a scheduler before the task declaration is also possible. |
| 35 | + # but we have to wait till it gets to task execution for the second time. |
| 36 | + worker_task = asyncio.create_task(run_receiver_task(dyn_broker)) |
| 37 | + scheduler_task = asyncio.create_task(run_scheduler_task(dyn_scheduler)) |
| 38 | + |
| 39 | + # We still able to send the task. |
| 40 | + await dyn_task.kiq(x=1) |
| 41 | + |
| 42 | + await asyncio.sleep(10) |
| 43 | + |
| 44 | + worker_task.cancel() |
| 45 | + try: |
| 46 | + await worker_task |
| 47 | + except asyncio.CancelledError: |
| 48 | + print("Worker successfully exited.") |
| 49 | + |
| 50 | + scheduler_task.cancel() |
| 51 | + try: |
| 52 | + await scheduler_task |
| 53 | + except asyncio.CancelledError: |
| 54 | + print("Scheduler successfully exited.") |
| 55 | + |
| 56 | + await dyn_broker.shutdown() |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + asyncio.run(main()) |
0 commit comments