Set Timeouts

Understand the details of game processes time out when they’re inactive.

We'll cover the following

There’s another case we need to handle before we’re done with this section. What happens if a player starts a game and then abandons it somewhere along the way? We don’t want to let those processes just sit there taking up system resources.

Fortunately, GenServer gives us an automated way to have processes time out and shut themselves down if they haven’t received a new message in a given number of milliseconds. We just need to do is add a fourth element to any of the GenServer reply tuples. This will be a positive integer representing the number of milliseconds to wait before timing out {:reply, :some_reply, %{}, 1000}.

Setting a test timeout

Let’s add some modifications to the Game module so game processes time themselves out when they’re inactive. First, let’s set a module attribute to fifteen seconds—long enough to write quick commands in IEx, but short enough to wait for:

@timeout 15000

Then, let’s add it to the return tuple for Game.init/1:

{:ok, %{player1: player1, player2: player2, rules: %Rules{}}, @timeout}

Get hands-on with 1200+ tech skills courses.