Alternative to Sleep in Genserver

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