Files
2026-03-09 23:09:46 -04:00

95 lines
2.9 KiB
Clojure

(ns Task
"Elixir Task module — convenient process abstraction for async computation.
In CljElixir: (Task/async (fn [] (expensive-work))), etc.
Tasks are processes meant to run a single action and return a result.")
(defn async
"Starts a task linked to the caller. Returns a Task struct.
(let [t (Task/async (fn [] (compute-result)))]
(Task/await t)) ;=> result"
([fun])
([module function-name args]))
(defn await
"Awaits a task reply. Raises on timeout (default 5000ms).
(Task/await task) ;=> result
(Task/await task 10000) ;=> with 10s timeout"
([task])
([task timeout]))
(defn await-many
"Awaits multiple tasks. Returns a list of results.
(Task/await-many [task1 task2 task3]) ;=> [result1 result2 result3]
(Task/await-many tasks 10000) ;=> with 10s timeout"
([tasks])
([tasks timeout]))
(defn yield
"Temporarily yields for a reply. Returns {:ok result}, {:exit reason}, or nil.
(Task/yield task 5000) ;=> {:ok result} or nil (if still running)"
([task])
([task timeout]))
(defn yield-many
"Yields on multiple tasks. Returns [{:ok result} | {:exit reason} | nil ...].
(Task/yield-many [task1 task2] 5000)"
([tasks])
([tasks opts-or-timeout]))
(defn start
"Starts a task that is not linked. Useful for fire-and-forget.
(Task/start (fn [] (send-email)))"
([fun])
([module function-name args]))
(defn start-link
"Starts a linked task. Useful under a supervisor.
(Task/start-link (fn [] (do-work)))"
([fun])
([module function-name args]))
(defn shutdown
"Shuts down a task. Returns {:ok reply}, {:exit reason}, or nil.
(Task/shutdown task) ;=> {:ok result}
(Task/shutdown task :brutal-kill) ;=> force shutdown"
([task])
([task timeout-or-brutal]))
(defn ignore
"Ignores an existing task. The task continues but its result is discarded.
(Task/ignore task)"
[task])
(defn completed
"Creates an already-completed task with the given `result`.
(Task/completed {:ok \"cached\"}) ;=> a task that immediately resolves"
[result])
(defn async-stream
"Returns a stream that runs the given function concurrently on each element.
(Task/async-stream [1 2 3] (fn [x] (expensive x)) :max-concurrency 4)"
([enumerable fun])
([enumerable fun opts])
([enumerable module function-name opts]))
(defn Supervisor.start-link
"Starts a Task.Supervisor. Use with async_nolink for fault-tolerant tasks."
([opts]))
(defn Supervisor.async
"Starts an async task under a Task.Supervisor.
(Task/Supervisor.async supervisor (fn [] (do-work)))"
([supervisor fun])
([supervisor fun opts])
([supervisor module fun args])
([supervisor module fun args opts]))
(defn Supervisor.async-nolink
"Like Supervisor.async but doesn't link. Safe for untrusted work.
(Task/Supervisor.async-nolink supervisor (fn [] (risky-work)))"
([supervisor fun])
([supervisor fun opts])
([supervisor module fun args])
([supervisor module fun args opts]))