Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply timeout on method in Erlang?

Is there a way to apply timeout on simple module method call, As example,

my_method(Name)->
  timer:sleep(2000),
  io:format("hello world ~p!~n",[Name]).

I want to add timeout option to above method, is there a way to do it?

like image 392
Hasitha Avatar asked Nov 21 '25 05:11

Hasitha


1 Answers

You could spawn your function and wait for a a message back. You can set a timeout while you wait on the receive.

 my_method(Name)->
  YourTimeOut = 10,
  Self = self(),
  _Pid = spawn(fun()-> 
                  timer:sleep(2000),
                  io:format("hello world ~p!~n",[Name]),
                  Self ! {self(), ok} end),
  receive
    {_PidSpawned, ok} -> ok
  after
     YourTimeOut -> timout
  end.
like image 167
Asier Azkuenaga Avatar answered Nov 22 '25 20:11

Asier Azkuenaga