How to Use Anonymous Functions
Learn to create anonymous functions and explain some callback functions.
Implement handle_continue
We return {:ok, state, {:continue, :run}}
from the init/1
callback, so we have to handle this message next. Within the handle_continue/2
callback, we perform the required work as soon as the process finishes initializing:
#file path -> jobber/lib/jobber/job.exdef handle_continue(:run, state) donew_state = state.work.() |> handle_job_result(state)if new_state.status == "errored" doProcess.send_after(self(), :retry, 5000){:noreply, new_state}elseLogger.info("Job exiting #{state.id}"){:stop, :normal, new_state}endend
Since the work
attribute is an anonymous function, we invoke it using the state.work.()
syntax and process the result.
We use the status
attribute to determine whether or not we need to retry the job. If the status is errored
, we schedule another attempt in five seconds and keep the process running. Otherwise, we stop the process for done
and failed
, since there isn’t any work left to do.
Handle the result
We need to consider three different outcomes when handling the result:
-
Success: This is when the job completes and returns
{:ok,
...