我会看看 Elixir Task module。
您可以使用Task.yield 或多个任务Task.yield_many 在给定的时间间隔内处理单个任务,尽管Task.yield 似乎更接近您可能需要的内容。
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()