A Periodical.Coordinator that keeps claims in Redis or KeyDB.
Every instance that shares a named Periodical schedule claims each run with one atomic command,
SET <prefix><key> <token> NX PX <ttl_ms>and the instance whose SET succeeds runs the callback. The lease expires
on the Redis server's clock, so the instances' own clock skew does not
affect it. Nothing needs cleaning up: expired claims disappear by
themselves.
Configuration
Start a Redix connection in your supervision tree and name it:
children = [
{Redix, {System.fetch_env!("REDIS_URL"), [name: MyApp.Redix]}},
# ...
]
config :periodical, Periodical.Config,
coordinator: {PeriodicalRedis, connection: MyApp.Redix}Options:
:connection(required) — theRedixconnection: a registered name or pid.:prefix— prepended to every key;"periodical:"by default. Give each application sharing a Redis its own prefix if their schedule names could collide.:timeout— milliseconds to wait for Redis; 5 000 by default.
The connection must be started before Periodical's scheduler fires its first
coordinated occurrence. A connection that is down makes claims fail with an
error, which Periodical's :coordinator_error policy handles.
KeyDB
KeyDB speaks the same protocol and supports the same commands, including
the EVAL used to renew a lease, so the configuration is identical. With
active replication between KeyDB masters, a claim is only as atomic as the
replication: point all instances at the same master.
Renewal
renew/2 extends a lease only while it still holds this claim's token,
checked and extended in one Lua script, so it never extends a lease that
expired and was won by another instance in between.
Summary
Functions
Claims the lease with SET NX PX.
Returns the Redis key a claim is stored under.
Extends the lease to claim.ttl_ms from now while the key still holds this claim's token.
Functions
@spec claim(Periodical.Coordinator.Claim.t(), keyword()) :: :won | :lost | {:error, term()}
Claims the lease with SET NX PX.
Returns :won when the key was set, :lost when it already exists, and
{:error, reason} when Redis could not be reached or answered with an error.
@spec redis_key(Periodical.Coordinator.Claim.t(), keyword()) :: String.t()
Returns the Redis key a claim is stored under.
iex> claim = %Periodical.Coordinator.Claim{key: "abc", name: :x, scheduled_at: ~U[2026-01-01 00:00:00Z], token: "t", ttl_ms: 1}
iex> PeriodicalRedis.redis_key(claim, [])
"periodical:abc"
iex> PeriodicalRedis.redis_key(claim, prefix: "billing:")
"billing:abc"
@spec renew(Periodical.Coordinator.Claim.t(), keyword()) :: :ok | :lost | {:error, term()}
Extends the lease to claim.ttl_ms from now while the key still holds this claim's token.
Returns :lost when the key expired or now belongs to another claim.