So let\'s say I want to send a bunch of emails or recreate sitemap or whatever every 4 hours, how would I do that in Phoenix or just with Elixir?
I find :timer.send_interval/2 slightly more ergonomic to use with a GenServer
than Process.send_after/4
(used in the accepted answer).
Instead of having to reschedule your notification each time you handle it, :timer.send_interval/2
sets up an interval on which you receive a message endlessly—no need to keep calling schedule_work()
like the accepted answer uses.
defmodule CountingServer do
use GenServer
def init(_) do
:timer.send_interval(1000, :update)
{:ok, 1}
end
def handle_info(:update, count) do
IO.puts(count)
{:noreply, count + 1}
end
end
Every 1000 ms (i.e., once a second), IntervalServer.handle_info/2
will be called, print the current count
, and update the GenServer's state (count + 1
), giving you output like:
1
2
3
4
[etc.]