我正在尝试实现一个GenServer
来监控我的一个功能,然后在1小时后重启该过程。如果我第一次体验GenServer
,那就原谅我缺乏知识。
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
函数。谢谢你的帮助。
答案 0 :(得分:2)
use Quantum.Scheduler
已为您定义start_link/0
和start_link/1
。您不能在同一模块中use Quantum.Scheduler
和use GenServer
,在不同的模块中定义它们。