betinajessen

betinajessen

How to run a job periodically

How can I schedule code to run every few hours in Elixir or Phoenix framework?

So let’s say I want to send a bunch of emails or recreate sitemap or whatever every 4 hours, how would I do that in Phoenix or just with Elixir?

Most Liked

dimitarvp

dimitarvp

I recommend you to make a small GenServer that you put in your app’s supervision tree – so it stays alive for as long as the app is live – and have it do something like this:

defmodule PeriodicWorker do
  use GenServer

  @impl true
  def init(period_in_millis) do
    # The `{:continue, :init}` tuple here instructs OTP to run `handle_continue`
    # which in this case will fire the first `:do_stuff` message so the worker
    # does its job once and then schedules itself to run again in the future.
    # Without this you'd have to manually fire the message to the worker
    # when your app starts.
    {:ok, period_in_millis, {:continue, :init}}
  end

  def handle_continue(:init, period_in_millis) do
    GenServer.call(self(), {:do_stuff, period_in_millis})
  end

  @impl true
  def handle_call(:do_stuff, _caller_pid, period_in_millis) do
    do_the_thing_you_need_done_periodically_here()

    schedule_next_do_stuff(period_in_millis)

    # or change `:ok` to the return value of the function that does the real work.
    {:reply, :ok}
  end

  def schedule_next_do_stuff(period_in_millis) do
    Process.send_after(self(), :do_stuff, period_in_millis)
  end
end

You can then supervise it like this in your app:

defmodule YourApp do
  use Application

  def start(_type, _args) d
    children = [
      {PeriodicWorker, 4 * 60 * 60 * 1000}, # 4 hours
      # ... other children ....
    ]

    options = [strategy: :one_for_one, name: YourApp.Supervisor]
    Supervisor.start_link(children, options)
  end
end

Not tested but I’ve done this a number of times and it should match reality closely enough.

derpycoder

derpycoder

Here’s a concrete example, so you can copy and learn from it.

Clone the Plausible Analytics repo, and search by Oban.Worker, you will see tons of example!!

Some Excerpts:

for site <- sites do
    SendEmailReport.new(%{site_id: site.id, interval: "weekly"},
      scheduled_at: monday_9am(site.timezone)
    )
    |> Oban.insert!()
end

def monday_9am(timezone) do
    Timex.now(timezone)
    |> Timex.shift(weeks: 1)
    |> Timex.beginning_of_week()
    |> Timex.shift(hours: 9)
end

OR

for site <- sites do
    SendEmailReport.new(%{site_id: site.id, interval: "monthly"},
      scheduled_at: first_of_month_9am(site.timezone)
    )
    |> Oban.insert!()
end

def first_of_month_9am(timezone) do
    Timex.now(timezone)
    |> Timex.shift(months: 1)
    |> Timex.beginning_of_month()
    |> Timex.shift(hours: 9)
end

EmailReports Module

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"interval" => "weekly", "site_id" => site_id}}) do
    # Send weekly report email
  end

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"interval" => "monthly", "site_id" => site_id}}) do
    # Send monthly report email
  end
derpycoder

derpycoder

Here’s a site I found that mentions 3 ways to get it done:

https://blog.kommit.co/3-ways-to-schedule-tasks-in-elixir-i-learned-in-3-years-working-with-it-a6ca94e9e71d

The first approach is GenServer which @dimitarvp mentioned.

If your requirements are not complex, you don’t need instrumentation and are not running in distributed mode, then you don’t need anything more.

But if you would like something more, checkout: Oban Git & Documentation

Oban: Robust job processing in Elixir, backed by modern PostgreSQL. Reliable,
observable and loaded with enterprise grade features.

AstonJ

AstonJ

You may also be interested in previous threads on this topic:

:smiley:

cmo

cmo

It depends how accurate you want it to be. If that release is restarted when the timer is a 1min then it’s going to be 1min between those two jobs. You could persist last_executed_at and use that to determine the initial delay.

Oban is a library option.

Where Next?

Popular in Questions Top

openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement