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
:
#file path -> jobber/lib/jobber/job.exdefp 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
:
#file path -> jobber/lib/jobber/job.exdef start_link(args) doargs =if Keyword.has_key?(args, :id) doargselseKeyword.put(args, :id, random_job_id())endid = 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 also pass down the ...