TIL: Cancel the scheduled send_after message

In production code, especially with GenServer, it is common to execute action again after a specific time. Many times this is just the process sending a message to itself. Most often it will be prepared as Process.send_after(self(), :message_event, after_x_ms).

It may happen that after some time, the conditions will change. Executing the planned action will not be needed or will even be incorrect. Have you ever wondered how you can cancel such a message?

For this purpose, we can use Process.cancel_timer/2. It is necessary to remember the references to the timer. We can use, for example, the state of GenServer.

See how easy it can be presented in the code:

# inside schedule flow
timer_ref = Process.send_after(self(), :message_event, 5_000)

# inside cancel flow

A really simple solution and will cancel redundant processing. It probably can be helpful in your project too!

Get new posts and extra comments

You'll receive every new post with extra unpublished comments available only to the subscribers!

I won't send you spam. Unsubscribe at any time.