Search code examples
elixirphoenix-frameworkgen-server

Understanding Genserver - start_link/0 conflicts with default


I'm trying implement a GenServer to monitor one of my functions and then restart the process after 1 hour. Forgive the lack of knowledge as this if my first experience with 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

I want this code to restart my check_question/0 function after one hour if if fails to find the table row in the database. I've received some help for this answer here. I think this is very close to what I want but I'm getting this error at compile time:

Error:

** (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

APPLICATION

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, [])
    ]

SOLUTION:

I need to restart the check_question function if it doesn't find a question from the database. Thanks for the help.


Solution

  • use Quantum.Scheduler is already defining a start_link/0 and start_link/1 for you. You cannot use Quantum.Scheduler and use GenServer in the same module, define them in different ones.