This commit is contained in:
Marc-Eric Martel
2023-10-22 10:39:08 -04:00
commit a8ffb43ec8
12 changed files with 231 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
defmodule GlobalBackgroundJob do
@moduledoc """
Documentation for `GlobalBckJob`.
"""
@doc """
Hello world.
## Examples
iex> GlobalBackgroundJob.hello()
:world
"""
def hello do
:world
end
end

View File

@@ -0,0 +1,42 @@
defmodule GlobalBackgroundJob.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
# Starts a worker by calling: GlobalBckJob.Worker.start_link(arg)
# {GlobalBackgroundJob.Worker, arg}
{Cluster.Supervisor, [topologies(), [name: GlobalBackgroundJob.ClusterSupervisor]]},
{GlobalBackgroundJob.DatabaseCleaner.Starter,[timeout: :timer.seconds(2)]}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: GlobalBackgroundJob.Supervisor]
Supervisor.start_link(children, opts)
end
defp topologies do
[
background_job: [
strategy: Cluster.Strategy.Gossip,
config: [
# port: 45892,
if_addr: "10.13.4.143",
multicast_if: "10.13.4.143", #addr locale
multicast_addr: "255.255.255.255",
multicast_ttl: 1,
secret: "secret",
broadcast_only: true
]
]
]
end
end

View File

@@ -0,0 +1,29 @@
defmodule GlobalBackgroundJob.DatabaseCleaner do
use GenServer
require Logger
alias __MODULE__.Runner
@impl GenServer
def init(args \\ []) do
timeout = Keyword.get(args, :timeout)
schedule(timeout)
{:ok, timeout}
end
@impl GenServer
def handle_info(:execute, timeout) do
Task.start(Runner, :execute, [])
schedule(timeout)
{:noreply, timeout}
end
defp schedule(timeout) do
Process.send_after(self(), :execute, timeout)
end
end

View File

@@ -0,0 +1,12 @@
defmodule GlobalBackgroundJob.DatabaseCleaner.Runner do
require Logger
def execute do
random = :rand.uniform(1_000)
Process.sleep(random)
Logger.info("#{__MODULE__} #{random} Mucho trabajo!")
end
end

View File

@@ -0,0 +1,36 @@
defmodule GlobalBackgroundJob.DatabaseCleaner.Starter do
use GenServer
alias GlobalBackgroundJob.DatabaseCleaner
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
@impl GenServer
def init(opts) do
pid = start_and_monitor(opts)
{:ok, {pid, opts}}
end
@impl GenServer
def handle_info({:DOWN, _, :process, pid, _reason}, {pid,opts} = state) do
{:noreply, {start_and_monitor(opts), opts}}
end
defp start_and_monitor(opts) do
pid =
case GenServer.start_link(DatabaseCleaner, opts, name: {:global, DatabaseCleaner}) do
{:ok, pid} ->
pid
{:error, {:already_started, pid}} ->
pid
end
Process.monitor(pid)
pid
end
end