Demystifying Schedulers — Elixir
Quick start guide to implementing Schedulers in Elixir-Phoenix based application
Schedulers
are programs/applications responsible for handling/invoking some process in various ways at some defined frequency.
Why do we need Schedulers?
- Moving files from one storage to another, deleting old files at midnight
- Processing logs at midnight
- Dump or archive logs every hour
- Monitor failed transactions during the last x minutes
- Process orders at midnight for delivery
- Allow the application to accept requests during a specific time.
There could be many more scenarios in today’s Business Automation process, where you would require schedulers. And it doesn’t matter which technology you are working on, you will find some problems in the application and the solution would be to write schedulers.
In Linux — Shell scripting we have corn job, in OS we have long-term/short-term schedulers, in java, we have a quartz scheduler library.
Implementation
Here is an example of a scheduler running every minute and logging the message “I am alive”
defmodule Demo.Scheduler1 do
@moduledoc false
use GenServer
require Logger
@scheduler_frequency :timer.minutes(1)
def start_link(_opts) do
GenServer.start_link(__MODULE__, :ok)
end
@impl true
def init(:ok) do
poll()
{:ok, :ok}
end
@impl true
def handle_info(:refresh, _state) do
execute_task
poll()
{:noreply, :ok}
end
def execute_task do
Logger.info("I am alive")
# do something
end
defp poll do
Process.send_after(self(), :refresh, @scheduler_frequency)
end
end
GenServer
A GenServer is a process like any other Elixir process and it can be used to keep state, execute code asynchronously and so on. The advantage of using a generic server process (GenServer) implemented using this module is that it will have a standard set of interface functions and include functionality for tracing and error reporting. It will also fit into a supervision tree.
https://hexdocs.pm/elixir/1.12/GenServer.html
Refer to my repo to run it on your local
Thank you for reading!