235

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?

9 Answers 9

488

There is a simple alternative that does not require any external dependencies:

defmodule MyApp.Periodically do
  use GenServer

  def start_link(_opts) do
    GenServer.start_link(__MODULE__, %{})
  end

  def init(state) do
    schedule_work() # Schedule work to be performed at some point
    {:ok, state}
  end

  def handle_info(:work, state) do
    # Do the work you desire here
    schedule_work() # Reschedule once more
    {:noreply, state}
  end

  defp schedule_work() do
    Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours
  end
end

Now in your supervision tree:

children = [
  MyApp.Periodically
]

Supervisor.start_link(children, strategy: :one_for_one)
17
  • 210
    It's impossible not to love this language :) Aug 19, 2015 at 15:46
  • 3
    Where should I put this file? Under lib/ directory of Phoenix project? Where do the test go, to test/periodically/*?
    – EugZol
    Nov 21, 2015 at 18:59
  • 11
    In lib because it is a long running process. You can put the test whatever makes sense, maybe "test/my_app/periodically_test.exs". Nov 28, 2015 at 11:14
  • 28
    @CodyPoll :timer.send_interval is fine but keep in mind that the intervals will constant. So imagine you want to do something every minute and, in the future, the work itself takes more than a minute. In such cases, you'd be working all the time and your message queue would grow unbounded. The solution above will always wait the given period after the work is done. Jul 1, 2016 at 9:26
  • 5
    @JoséValim — Is the {MyApp.Periodically, []} construct a preferred equivalent to worker(MyApp.Periodically, []) in Elixir these days? Trying to find docs to confirm this but having trouble this morning. Absolutely love this example btw — very instructive. Playing around with it and having fun with using :continue etc. May 2, 2020 at 13:03
45

Quantum lets you create, find and delete jobs at runtime.

Furthermore, you can pass arguments to the task function when creating a cronjob, and even modify the timezone if you're not happy with UTC.

If your app is running as multiple isolated instances (e.g. Heroku), there are job processors backed by PostgreSQL or Redis, that also support task scheduling:

Oban: https://github.com/sorentwo/oban

Exq: https://github.com/akira/exq

Toniq: https://github.com/joakimk/toniq

Verk: https://github.com/edgurgel/verk

2
  • 1
    I think it will be an overkill for a lot of simple tasks that don't require it but thank you for the answer anyway. Aug 4, 2016 at 22:04
  • 1
    Having a list of libraries available was helpful for me. Sep 3, 2016 at 4:59
25

You can use erlcron for that. You use it like

job = {{:weekly, :thu, {2, :am}},
  {:io, :fwrite, ["It's 2 Thursday morning~n"]}}

:erlcron.cron(job)

A job is a 2-element tuple. The first element is a tuple that represents the schedule for the job and the second element is the function or an MFA(Module, Function, Arity). In the above example, we run :io.fwrite("It's 2 Thursday morning") every 2am of Thursday.

Hope that helps!

2
  • Yeah it's better than nothing, thank you. I will leave the question unanswered for a while, maybe there will be other suggestions Aug 19, 2015 at 10:27
  • 4
    You're welcome! There's also github.com/c-rack/quantum-elixir which is an elixir lib, if you prefer
    – Gjaldon
    Aug 19, 2015 at 10:47
8

I used Quantum library Quantum- Elixir.
Follow below instructions.

#your_app/mix.exs
defp deps do
  [{:quantum, ">= 1.9.1"},  
  #rest code
end



#your_app/mix.exs
def application do
  [mod: {AppName, []},
   applications: [:quantum,
   #rest code         
 ]]
end

#your_app/config/dev.exs
config :quantum, :your_app, cron: [
  # Every minute
  "* * * * *": fn -> IO.puts("Hello QUANTUM!") end
]

All set. Start the server by running below command.

iex -S mix phoenix.server 
1
  • This is like cronjobs Nov 9, 2018 at 23:31
6

I find :timer.send_interval/2 slightly more ergonomic to use with a GenServer than Process.send_after/4 (used in the accepted answer).

Instead of having to reschedule your notification each time you handle it, :timer.send_interval/2 sets up an interval on which you receive a message endlessly—no need to keep calling schedule_work() like the accepted answer uses.

defmodule CountingServer do
  use GenServer

  def init(_) do
    :timer.send_interval(1000, :update)
    {:ok, 1}
  end

  def handle_info(:update, count) do
    IO.puts(count)
    {:noreply, count + 1}
  end
end

Every 1000 ms (i.e., once a second), IntervalServer.handle_info/2 will be called, print the current count, and update the GenServer's state (count + 1), giving you output like:

1
2
3
4
[etc.]
1
  • 4
    Please keep in mind that this solution can lead to an overflowing queue if your interval is smaller than the time it takes to finish the task.
    – Joe Eifert
    Nov 9, 2020 at 12:23
1

Besides to use Process.send_after, you can also use :timer.apply_interval.

0
1

Normally we use Oban for this but it depends on the priority of the tasks. If you just want to run a job that should be running after a specific period of time. then you can also use Genserver.

Genservers start as our application is started. you can use periodic processes Process.send_after(self(), :work, time) and add handle_info to handle the work you want to do. I used this when i needed to add long polling to my project.

0

Quantum is great, we use it at work as a cron replacement with a phoenix front-end and we also add jobs in real-time which is very neat.

0

Crontab lib & :timer, send_after , GenState machine or GenServer.

Generally we define cron expression in elixir module, and later parsed in that module during init. https://hexdocs.pm/crontab/readme.html

we schedule a timer using this. Process.send_after(self(), :message, time) or :timer.send_interval/2 It returns timer ref, which can be stored in state, which can also be cancelled by the ref.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.