# Terminate a task

**URL:** <https://discourse.julialang.org/t/terminate-a-task/120855>\
**Category:** General Usage\
**Tags:** question, multithreading\
**Created:** [October 3, 2024, 11:51am UTC](https://discourse.julialang.org/t/terminate-a-task/120855 "2024-10-03T11:51:19Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![zoythum](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/zoythum/32/212389_2.png) [@zoythum](https://discourse.julialang.org/u/zoythum)\
**Post date:** [October 3, 2024, 11:51am UTC](https://discourse.julialang.org/t/terminate-a-task/120855/1 "2024-10-03T11:51:19Z")

</div>

I am using ZMQ to create a publisher subscriber infrastructure. The main problem I am facing is that the `recv` function blocks the execution of the code. I would like to spawn a Task that is responsible for receiving a new message and terminate it after a given timeout. Unfortunately I don’t know how to kill a running task. My code looks like this

```julia
function receive_msg(socket)
  msg = recv(socket)
  return msg
end

task = @async receive_msg(socket)
start_time = time()

while time() - start_time < max_time
  sleep(step)
end

if !istaskdone(task)
  kill task <-- missing part
else
  data = fetch(task)

```

How do I make sure to kill the running task or what is the best way to achieve the behavior I want?

---

<div class="post-metadata">

**Author:** ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)\
**Post date:** [October 3, 2024, 12:45pm UTC](https://discourse.julialang.org/t/terminate-a-task/120855/2 "2024-10-03T12:45:39Z")

</div>

As of today, there is no reliable (builtin) way of killing a task. Your best bet is to either create a `Timer` (if you need a timeout) and to close the socket the task is listening on, and handling that in the task listening on the socket.

---

<div class="post-metadata">

**Author:** ![sgaure](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sgaure/32/14779_2.png) [@sgaure](https://discourse.julialang.org/u/sgaure)\
**Post date:** [October 3, 2024, 1:03pm UTC](https://discourse.julialang.org/t/terminate-a-task/120855/3 "2024-10-03T13:03:22Z")

</div>

Alternatively, you can use zmq to read the socket. `zmq_recv` has a `flags` argument which can be set to `MSG_DONTWAIT`. Your task can use this flag to regularly poll to socket, and check for some termination condition (e.g. an `Atomic{Bool}` which is set when it’s time to die).
