【发布时间】:2018-06-30 09:34:35
【问题描述】:
我正在尝试实现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 函数。感谢您的帮助。
【问题讨论】:
标签: elixir phoenix-framework gen-server