Search⌘ K

Register New Processes and Query the Registry

Learn to register new processes and query the registry using the select function.

Register new processes

We make a few changes to job.ex. First, let’s add a helper function, via/2, to job.ex:

C++
#file path -> jobber/lib/jobber/job.ex
defp via(key, value) do
{:via, Registry, {Jobber.JobRegistry, key, value}}
end

This returns a tuple that conforms to the required naming specification. The format is always {:via, Registry, config}, where config is also a tuple and can either be {registry_process, key} or {registry_process, key, value}. We use the extra value element to store some useful metadata about the process. We label each job with a type description so it’s easier to find out what each process is doing.

Modify start_link

We can use the provided ID or generate one for the process’s name. Let’s move some of the existing logic in start_link/1:

C++
#file path -> jobber/lib/jobber/job.ex
def start_link(args) do
args =
if Keyword.has_key?(args, :id) do
args
else
Keyword.put(args, :id, random_job_id())
end
id = Keyword.get(args, :id)
type = Keyword.get(args, :type)
GenServer.start_link(__MODULE__, args, name: via(id, type))
end

We add an extra :name argument to GenServer.start_link/2 to name the process. We have to provide the :via tuple, generated by the via/2 helper function. We ...