chandradot99
chandradot99

Reputation: 3876

How to test elixir application with cron job in local

In my elixir application, I am implementing a cron job with this library https://github.com/quantum-elixir/quantum-core. Below is my code for the same.

defp deps do
  [{:quantum, "~> 2.2"},
   {:timex, "~> 3.0"}]
end

defmodule MyApp.Scheduler do
  use Quantum.Scheduler,
    otp_app: :my_app
end

defmodule MyApp.Application do
  use Application

  def start(_type, _args) do
    import Supervisor.Spec, warn: false

    children = [
      # This is the new line
      worker(MyApp.Scheduler, [])
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

Then i am configuring cron job to print message like this.

config :my_app, MyApp.Scheduler,
  jobs: [
    {"* * * * *", fn -> IO.puts("Hello QUANTUM!") end}
  ]

How can I test whether cron job is working or not in my local.I tried to use mix run but nothing seems to print the message.

Upvotes: 1

Views: 566

Answers (2)

Kevin Johnson
Kevin Johnson

Reputation: 1970

Cron jobs according to their default definition are limited to 1 minute intervals.

Consider the schedule below:

*     *     *   *    *        command to be executed
-     -     -   -    -
|     |     |   |    |
|     |     |   |    +----- day of week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of        month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)

The problem you were experiencing is that you ran your program, but exited before 1 minute elapsed, thinking it doesn't work.

If after one minute you still see nothing, then do :observer.start and double check that your supervision tree is up and running under Applications tab. Perhaps you forgot to include the startup of the Application supervision tree inside your mix file.

In such a case, all you need to do is include the following inside your mix file as applies to you specifically under the mod field:

  def application do
    [
      mod: {Cronjob.Application, []},
      extra_applications: [:logger]
    ]
  end

Of course, when you need to run tests it is utterly ridiculous to be waiting minutes just to confirm your code as need be.

It is for this reason that the extended form of cron jobs has been introduced, and is available by the library you are utilizing as well.

The following is the way to do it:

  jobs: [
    {{:extended, "* * * * * *"}, {Cronjob, :hello, []}},
  ],

Upvotes: 3

chandradot99
chandradot99

Reputation: 3876

My bad, I forgot to include the start up of the Application supervision tree inside the mix file.

  def application do
    [
      extra_applications: [:logger],
      mod: {CnabClient.Application, []}
    ]
  end

Upvotes: 0

Related Questions