How to create a 'cron-job' with Elixir modules?

I have a database with all transactions from my application, I would like to create a module that from time to time, check the records in sarch for approved transactions and then execute some kind of service, It is possible to achieve this with elixir? Start other appication just to do this looks like waste of resource. My first thought would be to use a cron-job that do querys and calls some module to execute the service, would be possible?

Oban provides a cron-like feature : Oban.Plugins.Cron — Oban v2.18.3
Quantum was also a popular library for this : Quantum.Scheduler – Quantum v2.0.0

4 Likes

If you need a more robust solution you could check for Oban as said previously. If you wanna go with a very basic approach that does not require external libs you could try implement something similar to this: poller/lib/poller.ex at main · lcezermf/poller · GitHub

A simple GenServer that calls itself from time to time and does some work.

2 Likes

For gen server option, here’s an example of an incredibly simple cron job I have just using Task running once per day:

defmodule MyApp.SomeWorker do
  use Task

  def start_link(_arg) do
    Task.start_link(&loop/0)
  end

  def loop() do
    receive do
    after
      60 * 60 * 1000 ->
        do_the_work()
        loop()
    end
  end

  defp do_the_work() do
    # ...
  end
end

Then just add it to your application’s supervision tree:

children = [
  # ...
  MyApp.SomeWorker,
  # ...
]

EDIT: Pls be aware this is exceptionally basic. It’s merely on a timer that will restart on every deploy. It is not true cron.

3 Likes