Skip to content

Instantly share code, notes, and snippets.

@collegeimprovements
Forked from trestrantham/periodic_task.ex
Created December 6, 2018 03:43
Show Gist options
  • Save collegeimprovements/cb8f26061299ad842590307aa5639b0c to your computer and use it in GitHub Desktop.
Save collegeimprovements/cb8f26061299ad842590307aa5639b0c to your computer and use it in GitHub Desktop.
Run a task periodically natively in Elixir
defmodule MyApp.Periodically do
use GenServer
def start_link do
GenServer.start_link(__MODULE__, %{})
end
def init(state) do
Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours
{:ok, state}
end
def handle_info(:work, state) do
# Do the work you desire here
# Start the timer again
Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours
{:noreply, state}
end
end
# In the supervision tree:
worker(MyApp.Periodically, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment