Last active
December 6, 2018 03:44
-
-
Save collegeimprovements/20df0651e64d7331247851cd7556fa89 to your computer and use it in GitHub Desktop.
Cron in Elixir Ref: https://dockyard.com/blog/2017/11/29/need-an-elixir-dependency-to-manage-recurring-jobs-not-so-fast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule KeycloakSync.Application do | |
# See https://hexdocs.pm/elixir/Application.html | |
# for more information on OTP Applications | |
@moduledoc false | |
use Application | |
def start(_type, _args) do | |
# List all child processes to be supervised | |
import Supervisor.Spec | |
children = [ | |
# Starts a worker by calling: KeycloakSync.Worker.start_link(arg) | |
# {KeycloakSync.Worker, arg}, | |
supervisor(Cis.Repo, []), | |
supervisor(Clsacom.Repo, []), | |
supervisor(KeycloakSync.Repo, []), | |
worker(KeycloakSync.Cron, []) | |
] | |
# See https://hexdocs.pm/elixir/Supervisor.html | |
# for other strategies and supported options | |
opts = [strategy: :one_for_one, name: KeycloakSync.Supervisor] | |
Supervisor.start_link(children, opts) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# my_app/lib/my_app/my_job/recurring_job.ex | |
defmodule MyApp.MyJob.RecurringJob do | |
@moduledoc """ | |
Responsible of handling my job's schedule. | |
* Runs job on start and every minute thereafter. | |
""" | |
use GenServer | |
alias MyApp.MyJob | |
def start_link() do | |
GenServer.start_link(__MODULE__, nil) | |
end | |
def init(_) do | |
schedule_initial_job() | |
{:ok, nil} | |
end | |
def handle_info(:perform, state) do | |
MyJob.perform() | |
schedule_next_job() | |
{:noreply, state} | |
end | |
defp schedule_initial_job() do | |
Process.send_after(self(), :perform, 5_000) # In 5 seconds | |
end | |
defp schedule_next_job() do | |
Process.send_after(self(), :perform, 60_000) # In 60 seconds | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment