Erlang gen_server 具有长时间运行的任务
美好的一天,
我有一个 gen_server 进程,它定期执行一些长时间运行的状态更新任务 handle_info
:
handle_info(trigger, State) ->
NewState = some_long_running_task(),
erlang:send_after(?LOOP_TIME, self(), trigger),
{noreply, NewState}.
但是当这样的任务运行时,整个服务器会变得无响应,并且对它的任何调用都会导致整个服务器崩溃:
my_gen_server:status().
** exception exit: {timeout,{gen_server,call,[my_gen_server,status]}}
in function gen_server:call/2
如何避免 gen_server 的阻塞? 当有人在任何时候调用 my_gen_server:status()
时,结果应该类似于: {好的,task_active}
Good day,
I have a gen_server
process which does some long-running state-updating tasks periodically inhandle_info
:
handle_info(trigger, State) ->
NewState = some_long_running_task(),
erlang:send_after(?LOOP_TIME, self(), trigger),
{noreply, NewState}.
But when such task runs, then whole server gets unresponsive and any call to it leads to whole server crash:
my_gen_server:status().
** exception exit: {timeout,{gen_server,call,[my_gen_server,status]}}
in function gen_server:call/2
How it is possible to avoid blocking of gen_server ?
And when one call my_gen_server:status()
at any time, the result should be something like:{ok, task_active}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在单独的进程中执行长时间运行的任务。让此进程通知 gen_server 其任务进度(即是否可以跟踪任务进度),或者让进程完成任务或失败,但至少通知 gen_server 任务结果。
让 gen_server 与执行此长时间运行任务的进程链接,并让 gen_server 知道 PID 或注册名称,以便在出现退出信号时,它可以将该重要进程的死亡与其余进程隔离开来。
execute the long running task in a separate process. Let this process inform the gen_server of its progress with the task (that is if the task's progress can be tracked) OR let the process complete the task or fail but at least inform the gen_server of the results of the task.
Let the gen_server be linked with the process doing this long running task, and let the gen_server know the PID or registered name so that in case of exit signals, it can isolate the death of that important process from the Rest.
这个调用不会导致崩溃,而只是导致一个可以捕获的异常:
但是,该调用将保留在服务器的队列中,并且在处理完当前消息后,它将发送一个回复消息:
{ServerRef, Reply}
,该消息应被调用进程丢弃。避免 Erlang 中任何进程(无论是否是 gen_server )阻塞的唯一方法是不要在其上运行阻塞任务。因此,另一种选择可能是在另一个进程上运行您的长任务,该进程仅与您的服务器通信,因此没有人关心它是否被阻止。
This call does not lead to a crash, but simply to an exception which can be caught:
However, the call will remain in the server's queue, and after it finishes handling the current message, it will send a reply message:
{ServerRef, Reply}
, which should be discarded by the calling process.The only way to avoid blocking of any process in Erlang (whether
gen_server
or not) is not to run blocking tasks on it. So another alternative could be to run your long tasks on a different process which only talks to your server, so nobody cares that it's blocked.