Hi, is there a way to check within my task code wh...
# ask-community
i
Hi, is there a way to check within my task code whether cancellation has been requested? I.e. within a potentially long operation I'd like to poll or be notified that cancellation was requested so I can raise an exception and end the task
I'm not seeing it on Context which is where I thought to check
k
Would you cancel from the Prefect UI in this scenario?
i
Either Prefect UI or call the Prefect API from another system
k
The immediate answer is no. The cancellation is aggressive and just stops processing. On the roadmap though are some form of hooks that you would let run after a cancellation. Github issue here .
i
I can't check in the task whether the status is "cancellation requested"?
k
You could poll try polling for it using the GraphQL API with the
get_task_run_info
route. You can supply the task id from the context, but I think the window between cancellation request and the task shutting down is pretty small. Once the task shuts down, that code is not running so I don’t think it’s reliable to depend on that error you want to raise being raised. Could you tell me more about what you’re trying to do?
i
Once the task cancel is requested, my experience is that the task run doesn't get terminated. What I'm thinking of is something like:
Copy code
@task
def my_task_fn():
    for i in range(SOME_LARGE_NUMBER):
        # do work
        if my_task_is_cancelled:
            raise Error("I'm cancelled!")
Using the DaskKubernetesEnvironment (slightly older release of Prefect) that loop will continue to run rather than exiting
I.e. if the loop takes an hour and you request cancellation 10 minutes in
k
Ah I see what you mean. Yes you are right that it’s hard to cancel work done being in other compute like Dask. Yes this is definitely a good idea to try. I would use the
get_task_run_info
and pull the state and check if it is
Cancelled
i
Ok. Just to check if I call
prefect.client.client.Client()
inside my task that was started by the Prefect agent it will get the auth information flowed through automatically?
k
Yes that’s right
i
Great, I'll give it a try. Thanks!