了解Genserver - start_link / 0与默认冲突

时间:2018-01-21 18:00:33

标签: elixir phoenix-framework gen-server

我正在尝试实现一个GenServer来监控我的一个功能,然后在1小时后重启该过程。如果我第一次体验GenServer,那就原谅我缺乏知识。

CODE:

defmodule Statcasters.Scheduler do
  use GenServer
  use Quantum.Scheduler,
    otp_app: :statcasters

  alias Statcasters.{Repo, Question, SportRadar.ActiveQuestion, SportRadar.Nba, SportRadar.Questions}
  require IEx

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

  def init(state) do
    check_question()
    {:ok, state}
  end

  def handle_info(:update, state) do
    check_question()
    {:noreply, state}
  end

  def check_question do
    case question = Repo.get_by(Question, active: true, closed: true) do

    question when not(is_nil(question)) ->
      case ActiveQuestion.ready_for_answer_status(question) do
        n when n in ["complete", "closed"] ->
          question
            |> Question.changeset(%{ready_for_answer: true, closed: true})
            |> Repo.update()
      end
    _ ->
      Process.send_after(self(), :update, 60*60*1000)
    end
  end
end

如果无法在数据库中找到表行,我希望此代码在一小时后重新启动check_question/0函数。我收到了一些关于这个答案的帮助here。我认为这非常接近我想要的但是我在编译时遇到了这个错误:

错误:

** (CompileError) lib/statcasters/scheduler.ex:13: def start_link/0 conflicts with defaults from start_link/1
    lib/statcasters/scheduler.ex:13: (module)
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:198: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6

应用

children = [
      # Start the Ecto repository
      supervisor(Statcasters.Repo, []),
      # Start the endpoint when the application starts
      supervisor(StatcastersWeb.Endpoint, []),
      supervisor(Statcasters.Scheduler, [], restart: :transient),
      # Start your own worker by calling: Statcasters.Worker.start_link(arg1, arg2, arg3)
      # worker(Statcasters.Worker, [arg1, arg2, arg3]),
      worker(Statcasters.Scheduler, [])
    ]

解:

如果找不到数据库中的问题,我需要重新启动check_question函数。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

use Quantum.Scheduler已为您定义start_link/0start_link/1。您不能在同一模块中use Quantum.Scheduleruse GenServer,在不同的模块中定义它们。