3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Elixirで定期実行 〜Quantum〜

Last updated at Posted at 2024-09-11

今回の仕様

  • 10秒に一度メッセージを表示
  • 1分に一度メッセージを表示

プロジェクト作成

スーパバイザツリーも一緒に作成

$ mix new quantum_experiment --sup
$ cd quantum_experiment

quantum追加

mix.exs
defmodule QuantumExperiment.MixProject do
   # 〜省略〜
  defp deps do
    [
+     {:quantum, "~> 3.0"}
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
    ]
  end
   # 〜省略〜
end
$ mix deps.get

残りのソース

ここに定期実行するタイミングを設定します

config/config.exs
import Config

config :quantum_experiment, QuantumExperiment.Scheduler,
  jobs: [
    {{:extended, "*/10 * * * *"}, {QuantumExperiment, :pirnt, ["10秒"]}},
    {"*/1 * * * *", {QuantumExperiment, :pirnt, ["1分"]}}
  ]

config :quantum_experiment, QuantumExperiment.Scheduler, debug_logging: false
lib/quantum_experiment/application.ex
defmodule QuantumExperiment.Application do
  # See https://hexdocs.pm/elixir/Application.html
  # for more information on OTP Applications
  @moduledoc false
  use Application

  @impl true
  def start(_type, _args) do
+   QuantumExperiment.pirnt("開始")
    children = [
      # Starts a worker by calling: QuantumExperiment.Worker.start_link(arg)
      # {QuantumExperiment.Worker, arg}
+     QuantumExperiment.Scheduler
    ]

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: QuantumExperiment.Supervisor]
    Supervisor.start_link(children, opts)
  end
end
lib/quantum_experiment/scheduler.ex
defmodule QuantumExperiment.Scheduler do
  use Quantum, otp_app: :quantum_experiment
end
lib/quantum_experiment.ex
defmodule QuantumExperiment do
  # 〜省略〜
  def pirnt(message) do
    "#{DateTime.utc_now()}:#{message}"
    |> IO.puts()
  end
end

リリース&実行

$ MIX_ENV=prod mix release
$ _build/prod/rel/quantum_experiment/bin/quantum_experiment start

実行結果

2024-09-11 20:30:27.375304Z:開始
2024-09-11 20:30:30.377932Z:10秒
2024-09-11 20:30:40.377856Z:10秒
2024-09-11 20:30:50.377814Z:10秒
2024-09-11 20:31:00.377606Z:10秒
2024-09-11 20:31:00.377638Z:1分
2024-09-11 20:31:10.377778Z:10秒
2024-09-11 20:31:20.377745Z:10秒
2024-09-11 20:31:30.377790Z:10秒
2024-09-11 20:31:40.377637Z:10秒
2024-09-11 20:31:50.377805Z:10秒
2024-09-11 20:32:00.377843Z:10秒
2024-09-11 20:32:00.377906Z:1分

ハマったこと

mix run

2024-09-11 20:30:27.375304Z:開始

と表示後終了してします

iex -S mixは終了せずに動きました
余分な表示をさせない為に結果「リリース&実行」の方法にたどりつきました

ソース(github)

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?