如何启动Elixir进程,然后在超时后将其杀死?我有这样的代码:
defmodule OperationsManager do
def run_operation do
spawn fn ->
# long operation
end
end
end
内部操作可能持续太长时间以至于无法等待其结束,因此我需要从管理器中终止该过程。我该怎么做?
编辑:
重要细节:我需要产生多个操作,并且所有这些操作都应具有单独的超时。
我来看看Elixir Task模块。
您可以在给定的时间间隔内使用一个Task.yield
或多个任务来处理单个任务Task.yield_many
,尽管Task.yield
看起来更接近您的需要。收益回报{:ok, result}
(成功回报),{:exit, reason}
(任务崩溃)或:nil
(超过超时间隔)。您也可以考虑将任务放在监管树中。
以下代码基于elixir 1.2.1。
defmodule OperationsManager do
def run_operation() do
task1 = Task.async(fn() -> operation("task 1", 1) end)
result = Task.yield(task1, 5000)
process_task(task1, result)
task2 = Task.async(fn() -> operation("task 2", 2) end)
task4 = Task.async(fn() -> operation("task 4", 4) end)
task6 = Task.async(fn() -> operation("task 6", 6) end)
task8 = Task.async(fn() -> operation("task 8", 8) end)
results = Task.yield_many([task2, task4, task6, task8], 7000)
for {task, res} <- results do
process_task(task, res)
end
end
def process_task(task, res) do
case res do
:nil ->
IO.write("shutting down timed out task: ")
IO.inspect(task)
Task.shutdown(task, :brutal_kill)
{:ok, task_number} ->
IO.puts("#{task_number} is complete")
{:exit, _reason} ->
# some logic when the task terminates
end
end
def operation(task_number, timeout) do
:timer.sleep(timeout * 1000)
task_number
end
end
OperationsManager.run_operation()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句