Timeouts in Crystal
Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in Crystal is straightforward using channels and select
.
Running this program shows the first operation timing out and the second succeeding.
In this Crystal version:
We use
require "time"
to access time-related functionality.Channels in Crystal are unbuffered by default, so we use
spawn
blocks to send messages asynchronously.The
select
statement in Crystal works similarly to Go, allowing us to wait on multiple channel operations.Instead of
time.After
, Crystal provides atimeout
macro that can be used directly inselect
statements.We define a
main
function and call it at the end of the file, as Crystal doesn’t have a specialmain
function like Go does.
This example demonstrates how to implement timeouts in Crystal using channels and select
, providing a way to bound execution time for operations that might take too long.