Demystifying Schedulers — Elixir

Ritresh Girdhar
2 min readNov 14, 2021

Quick start guide to implementing Schedulers in Elixir-Phoenix based application

Photo by Jon Tyson on Unsplash

Schedulers

are programs/applications responsible for handling/invoking some process in various ways at some defined frequency.

Why do we need Schedulers?

  1. Moving files from one storage to another, deleting old files at midnight
  2. Processing logs at midnight
  3. Dump or archive logs every hour
  4. Monitor failed transactions during the last x minutes
  5. Process orders at midnight for delivery
  6. 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!

--

--

Ritresh Girdhar

Father || Coder || Engineer || Learner || Reader || Writer || Silent Observer