I am setting up a GenServer that runs every hour to cache data. I followed the example José Valim posted is response to a question about how to do this.
How to run some code every few hours in Phoenix framework?
It works great except that if the interval I gave the call to Process.send_after/3
is a module attribute it does not run. Does anyone have insights as to why this might be?
So the following does not work but if in the calls to Process.send_after/3
I replace @interval
with 60 * 60 * 1000
it runs as expected (this is essentially the code from the other SO post above):
defmodule MyApp.Periodically do
use GenServer
def start_link do
GenServer.start_link(__MODULE__, %{})
end
@interval 60 * 60 * 1000
def init(state) do
Process.send_after(self(), :work, @interval)
{:ok, state}
end
def handle_info(:work, state) do
# Begin caching the new data.
MyApp.CacheManager.cache_new_data()
# Start the timer again
Process.send_after(self(), :work, @interval)
{:noreply, state}
end
end
send_after
quite often. Thus, I am sure it should work. Try outputting the interval before you use it and see what it is:IO.inspect @interval
. It is possible does not have the value you think it does. – Jason Harrelson1 * 2 * 1000
for quick testing, but it does run. – CoderDennis