Hi everyone,
I’m quite new to Elixir.
I have a module using GenServer. The calling code calls a method that gets some data, and I want to have it wait for a period before responding, with the calling code blocking until it responds.
I’ve seen comments that Process.sleep() inside a genserver call is bad. I think because it blocks the genserver from responding to further calls?
Could someone help explain the alternatives?
Thanks a lot,
Shawn
Process.send_after/4
- When you receive the message you want to delay processing,
send_after
another message to “yourself” that contains enough information to do the actual work - and do it when that message arrives.
- Use
:no_reply
in your handle_*
result (i.e. after the send_after
has been processed).
- You can use
GenServer.reply/2
to reply to the caller at that later time.
Example here
Building Non Blocking Erlang apps discusses the approach in more detail - the code is in Erlang but it’s similar enough.
6 Likes
Thanks very much @peerreynders. What you described worked perfectly!
Shawn