Testing Periodic Actions

Learn how to use GenServers as processes that do something periodically based on their state.

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
...