Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restart a supervised task that crashes

{:ok, tas} = Task.Supervisor.start_link(restart: :transient, max_restarts: 4)
a = 1
Task.Supervisor.async_nolink(tas, fn -> IO.puts "#{a}..." end)
Task.Supervisor.async_nolink(tas, fn ->
  IO.puts "Not Restarting :( "
  1 = 2
end)
a =  a + 1
Task.Supervisor.async_nolink(tas, fn -> IO.puts "#{a}.." end)
a =  a + 1
Task.Supervisor.async_nolink(tas, fn -> IO.puts "#{a}.." end)

The option restart: :transient does not seem to have any effect.

I've few tasks Task.async(fn(x) -> fetch_info(x) end that make an http request to get multiple resources, and has timeout error. It would be nice to retry those failing tasks, instead of using try, rescue.

I think async_nolink is the closest I got without crashing the process. If there is no way using Task, do we have a simpler approach using Supervisor that starts multiple process which exists once their job is done and restart them if they fail?

like image 368
Vysakh Sreenivasan Avatar asked Dec 18 '22 19:12

Vysakh Sreenivasan


1 Answers

You just have to use Task.Supervisor.start_child instead of Task.Supervisor.async_nolink to have the children properly restarted:

{:ok, tas} = Task.Supervisor.start_link(restart: :transient, max_restarts: 4)

Task.Supervisor.start_child(tas, fn -> 1 = 2 end) 
like image 51
user6200324 Avatar answered Dec 31 '22 11:12

user6200324