Periodic tasks with Elixir

No more Googling for Cron syntax

Using receive/1 for timeouts

defmodule Example dodef process() do
receive do
after
5_000 ->
IO.puts "5 seconds elapsed"
process()
end
end
end

Creating a periodic Task module

defmodule Example.BitcoinPriceUpdater do
use Task
def start_link(_arg) do
Task.start_link(&poll/0)
end
def poll() do
receive do
after
60_000 ->
get_price()
poll()
end
end
defp get_price() do
# Call API & Persist
IO.puts "To the moon!"
end
end
defmodule Example.Application do
@moduledoc false
use Application def start(_type, _args) do
children = [
Example.BitcoinPriceUpdater
]
opts = [strategy: :one_for_one, name: Example.Supervisor]
Supervisor.start_link(children, opts)
end
end
children = [
worker(Example.BitcoinPriceUpdater, [])
]

Freelance Developer • Founder of @CodeHalf • Rubyist • Elixir Alchemist • Wannabe Data Scientist • Dad

Freelance Developer • Founder of @CodeHalf • Rubyist • Elixir Alchemist • Wannabe Data Scientist • Dad