How to cancel activity

Is there a way to cancel an activity after some time?
The thing is activity is waiting for X hours if it was not canceled it does the work.
The signal came into my mind, but maybe there is a more elegant way to do so.

Assuming the activity is properly heartbeating and you have a reasonable heartbeat timeout, you cancel a started activity task just like you would any other asyncio task.

So you should be able to task = workflow.start_activity(...) + task.cancel() or task = asyncio.create_task(workflow.execute_activity(...)) + task.cancel() (they are essentially the same thing). This also means asyncio cancellation propagates through activity tasks (e.g. workflow cancellation cancels awaited activities, new 3.11 task groups, etc).

Just don’t forget the heartbeat timeout and to regularly heartbeat from the activity. Also, you may want to look at the cancellation_type option when starting the activity because it affects how activity cancellation is handled with regards to waiting on the cancellation to take effect (by default cancellation is issued but activity handling of the cancellation is not waited on, i.e. “try cancel”).

1 Like

Adding to what Chad said, there are docs that show how to cancel an Activity.

1 Like