Skip to content

Instantly share code, notes, and snippets.

@watsy0007
Created October 15, 2022 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watsy0007/fa51372e0d1733576b05225563ca3e20 to your computer and use it in GitHub Desktop.
Save watsy0007/fa51372e0d1733576b05225563ca3e20 to your computer and use it in GitHub Desktop.
elixir periodically
defmodule PeriodicWorker do
use GenServer
@impl true
def init(period_in_millis) do
# The `{:continue, :init}` tuple here instructs OTP to run `handle_continue`
# which in this case will fire the first `:do_stuff` message so the worker
# does its job once and then schedules itself to run again in the future.
# Without this you'd have to manually fire the message to the worker
# when your app starts.
{:ok, period_in_millis, {:continue, :init}}
end
def handle_continue(:init, period_in_millis) do
GenServer.call(self(), {:do_stuff, period_in_millis})
end
@impl true
def handle_call(:do_stuff, _caller_pid, period_in_millis) do
do_the_thing_you_need_done_periodically_here()
schedule_next_do_stuff(period_in_millis)
# or change `:ok` to the return value of the function that does the real work.
{:reply, :ok}
end
def schedule_next_do_stuff(period_in_millis) do
Process.send_after(self(), :do_stuff, period_in_millis)
end
end
defmodule YourApp do
use Application
def start(_type, _args) d
children = [
{PeriodicWorker, 4 * 60 * 60 * 1000}, # 4 hours
# ... other children ....
]
options = [strategy: :one_for_one, name: YourApp.Supervisor]
Supervisor.start_link(children, options)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment