Terminate a task

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

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?

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.

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).