gen_worker

Worker behavior that helps to run task at a specific time with a specified frequency.


Keywords
elixir-lang, hex, package, scheduler, worker
License
MIT

Documentation

GenWorker

Elixir CI Hex pm Coverage Status

Generic Worker behavior that helps to run task at a specific time with a specified frequency.

Installation and usage

It's available in Hex, the package can be installed as:

  1. Add gen_worker to your list of dependencies in mix.exs:
def deps do
  [
    {:gen_worker, ">= 0.0.1"}
  ]
end

Then run mix deps.get to get the package.

  1. Define your business logic:
defmodule MyWorker do
  use GenWorker, run_at: [hour: 13, minute: 59], run_each: [days: 1]

  def run do
    IO.puts "MyWorker run every day at 13:59"
  end
end
  1. Add it to the application supervision tree:
def start(_type, _args) do
  import Supervisor.Spec, warn: false

  children = [
    worker(MyWorker, [])
    # ...
  ]

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

Documentation can be found at https://hexdocs.pm/gen_worker.

Supported options

run_at – keyword list with integers values. Supported keys: :year, :month, :day, :hour, :minute, :second, :microsecond.

Or you can use map for multiple runs:

use GenWorker, run_at: %{"some_key" => [hour: 13, minute: 59], "other_key" => [hour: 14, minute: 00]}, run_each: [days: 1]

run_each - keyword list with integers values. Supported keys: :years, :months, :weeks, :days, :hours, :minutes, :seconds, :milliseconds. Default: [days: 1].

timezone - valid timezone. Default: :utc.

Configuration

You can define callbacks to all workers:

  • init -> calls on initializing worker
  • before -> calls each time before worker task starts
  • finally -> calls each time on the end worker task

For exampLe it could be used in the tests test_helper.exs

  GenWorker.configure(fn c ->
    c.init(fn _module, _args ->
      :ok = Ecto.Adapters.SQL.Sandbox.checkout(App.Repo)
      Ecto.Adapters.SQL.Sandbox.mode(Repo, {:shared, self()})
      :ok
    end)
  end)

License

This software is licensed under the MIT license.