Skip to content

Instantly share code, notes, and snippets.

@aayushmau5
Last active March 23, 2024 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aayushmau5/82fe80bdff25613b9e7cf443ec9f6286 to your computer and use it in GitHub Desktop.
Save aayushmau5/82fe80bdff25613b9e7cf443ec9f6286 to your computer and use it in GitHub Desktop.
defmodule TaskRunnerGenServer do
use GenServer
@impl true
def init(%{remote_node: remote_node} = args) do
# GenServer.start_link(TaskRunnerGenServer, %{remote_node: "REMOTE_NOTE_AT0M"}, name: TaskRunnerGenServer)
{:ok, %{ref: nil, node: remote_node}}
end
def start_task do
GenServer.call(__MODULE__, :start_task)
end
@impl true
def handle_call(:start_task, _from, %{ref: ref} = state) when is_reference(ref) do
{:reply, :ok, state}
end
def handle_call(:start_task, _from, %{ref: nil, node: node} = state) do
# ModuleName.TaskRunner -> Make sure you have a task supervisor running on remote node
task = Task.Supervisor.async_nolink({ModuleName.TaskRunner, node}, ModuleName.Stats, :module_function, [])
dbg(task)
{:reply, :ok, %{state | ref: task.ref}}
end
@impl true
def handle_info({ref, answer}, %{ref: ref} = state) do
Process.demonitor(ref, [:flush]) # We don't care about the DOWN message now, so let's demonitor and flush it
IO.inspect(answer)
{:noreply, %{state | ref: nil}}
end
# The task failed
def handle_info({:DOWN, ref, :process, pid, reason}, %{ref: ref} = state) do
# Log and possibly restart the task...
IO.inspect(reason)
{:noreply, %{state | ref: nil}}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment