Testing Periodic Actions
Learn how to use GenServers as processes that do something periodically based on their state.
We'll cover the following
A common use for GenServers is to have a process in your system that acts periodically. For example, you could have a GenServer that resets a cache every five minutes or a GenServer that looks for changes to system environment variables every few seconds and updates other parts of your system when that happens.
SoggyWaffle
For our Soggy Waffle application, we need something like what we just described. Soggy Waffle’s purpose is to alert us if there will be rain in the next few hours. To do that, the application needs to periodically call out to the weather API to check if there’s rain in the forecast for a given location.
Remember the weather API we worked within Unit Tests, and Integration and End-to-End Tests. We’ll finally be able to put that to real use.
However, just performing weather API calls periodically and alerting if there’s rain in the next few hours isn’t enough to make this work properly. The application also needs to avoid alerting us every time the forecast says it will rain in two hours. If we are checking the API every 30 minutes, we can’t also be sending an alert every thirty minutes. We need to store some data somewhere that’ll help us avoid useless alerts.
So our use case is clear:
- Perform some periodic action.
- Store some state.
It seems like our best tool to solve this is a GenServer. What a plot twist.
We have one more detail to cover. We want Soggy Waffle to alert us through SMS. To send SMSs, we’ll use a third-party integration such as Twilio. Soggy Waffle will talk to Twilio via HTTP, and Twilio will deal with the nitty-gritty details of sending SMSs.
Instead of diving into the details of what the code to interact with Twilio looks like, we’ll just look at the interface to Twilio that we’ll use.
Rememer: When isolating parts of our Testing Periodic Actions system, we mostly care about the interfaces that those isolated parts expose. The internals are a different concern.
Here’s the interface we’ll have available:
Get hands-on with 1200+ tech skills courses.