How to run locally scheduled flow in Prefect V2

310 Views Asked by At

I used to work with local scheduled flows in prefect v1 like :

from prefect import Flow, Task
from prefect.schedules import CronSchedule

@Task
def hello_world():
   print("hello world")

with Flow(name="Hello", schedule=CronSchedule("*/5 * * * *")) as flow:

   hello_world()

flow.run()

And I want to use a similar logic with prefect v2 but the doc is based on deployment.

Is it forced to use a deployment to do that and if its the case is there a specific deployment which only run the flow every 5 minute and do not use a server to show an UI.

My base code for this in prefect v2 is :

from prefect import flow, task

@task
def hello_world():
    print("hello world")


@flow(flow_run_name="{name}-on-{date:%A}")
def flow_main(name="flow_main", date: datetime.datetime):
    hello_world()

flow_main()
1

There are 1 best solutions below

0
jeffhale On

In Prefect 2 you do need a deployment to create a schedule for a flow. You can now do that quickly with the .serve() method.

For example - just run this script to create a local server, deployment, and cron schedule all at once.

from prefect import flow

@flow(log_prints=True)
def testing():
    print("hello world")

if __name__ == "__main__":
    testing.serve(name="my-first-deployment", cron="0 0 * * *")

See the docs for more info: https://docs.prefect.io/2.13.4/getting-started/quickstart/