|
| 1 | +import asyncio |
| 2 | +from datetime import timedelta |
| 3 | + |
| 4 | +import flyte |
| 5 | +import flyte.report |
| 6 | + |
| 7 | +env = flyte.TaskEnvironment( |
| 8 | + name="long_running_reuse", |
| 9 | + image=flyte.Image.from_debian_base().with_pip_packages("unionai-reuse"), |
| 10 | + reusable=flyte.ReusePolicy( |
| 11 | + replicas=1, |
| 12 | + concurrency=2, |
| 13 | + idle_ttl=timedelta(minutes=5), |
| 14 | + ) |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +@env.task(report=True) |
| 19 | +async def long_running_task(duration: timedelta) -> str: |
| 20 | + """ |
| 21 | + A task that simulates a long-running operation. |
| 22 | + It periodically reports a heartbeat to report.log to indicate progress, |
| 23 | + every minute. |
| 24 | + """ |
| 25 | + import time |
| 26 | + |
| 27 | + start_time = time.time() |
| 28 | + end_time = start_time + duration.total_seconds() |
| 29 | + while time.time() < end_time: |
| 30 | + elapsed = time.time() - start_time |
| 31 | + await flyte.report.log.aio(f"<p>Elapsed time: {elapsed:.2f} seconds</p>", do_flush=True) |
| 32 | + await asyncio.sleep(60) |
| 33 | + |
| 34 | + |
| 35 | +@env.task(report=True) |
| 36 | +async def main_task(duration: timedelta) -> str: |
| 37 | + """ |
| 38 | + The main task that calls the long-running task. |
| 39 | + """ |
| 40 | + await flyte.report.log.aio("<h1>Starting long-running task</h1>", do_flush=True) |
| 41 | + t = asyncio.create_task(long_running_task(duration=duration)) |
| 42 | + while not t.done(): |
| 43 | + await asyncio.sleep(60) |
| 44 | + await flyte.report.log.aio("<h1>Long-running task still in progress</h1>", do_flush=True) |
| 45 | + return await t |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + flyte.init_from_config("../../config.yaml") |
| 50 | + run = flyte.run(main_task, duration=timedelta(days=5)) |
| 51 | + print(run.url) |
| 52 | + |
| 53 | + |
0 commit comments