When experimenting with a new language, I always try to pick up some small problem in order to apply what I read. This time, I’m creating a minesweeper game which, right now, you can only play it through telnet.
While trying to better understand how Supervisors work in Erlang, I created a small example that uses the Erlang API, rather than using the facilities provided by Elixir’s
I’m using the great Learn You Some Erlang for Great Good! for reference. To make my example, I created two modules:
Wkr, respectively representing supervisor and workers. You can copy and paste the following code on
Sup is started through the start_link function, which receives a list of type atoms. Each given type will become a new worker. The types are
unstable, meaning a worker that will always run without problems, and another that will crash.
It then calls the
start_link function on the Erlang
supervisor module, which in turn will call the
init function of the given module. In this case, the given module is
Sup itself through the
init will build the spec that is used to describe the supervisor behavior and workers. More details about the parameters can be found here.
For each worker, the function
Wkr.start_link will be called, spawning their event loop.
For instance, you can start two workers, a good and a bad one, with the following code:
If you follow the printed messages, you’ll see that the worker #0 will crash and be automatically restarted.
If you keep it running, eventually the whole supervisor will shutdown. That happens because I set the supervisor to “give up” in case there were 5 crashes on the last 60 seconds.
To prevent that, you can dynamically terminate the problematic child, and also delete its spec:
- Services Version Lock with Docker and Jenkins
- Using Dialyzer with an Elixir Mix Project
- Erlang Link, Monitor, and Process Exit
- Problems with Branches per Environment
- Efficient Timer using a Circular Buffer
- Secure Configuration Management for Microservices
- Proxy annotated objects with Guice
- Tips for your Distributed Project Inception or Meeting
- RFID, Dryers, and IoT
- Blockchains as Part of the IoT Architecture