How To Sleep In Ruby

In this blog post, we will discuss the sleep method in Ruby, which is used to pause the execution
of a script for a specified amount of time. This is often useful when you need to wait for an external resource
or simply control the pacing of your script. Let’s dive in and explore how to use the sleep method
and some common use cases.

Basic Usage

Using the sleep method in Ruby is quite simple. It takes a single argument, which represents the
number of seconds to pause the execution of the script. For example, if you want to pause your script for 5
seconds, you can use the following code:

sleep(5)

The above code will cause the script to pause for 5 seconds before continuing with the next line of code. Note
that the argument passed to sleep can be a decimal number if you need a more precise duration. For
example, to sleep for half a second, you can use:

sleep(0.5)

Examples

1. Waiting for an External Resource

One common use case for the sleep method is when you need to wait for an external resource, such as
an API response or a file to be created. For example, let’s say you’re making an API call that takes a few
seconds to return the result, and you want to pause your script while waiting for the response. You can use the
following code:

puts 'Making API call...'
response = nil
until response do
  sleep(1)
  response = get_api_response
end
puts 'API response received!'

In this example, we’re using a loop to keep checking for the API response and using sleep to pause
the script for 1 second between each check.

2. Pacing a Script

Sometimes, you may want to control the pacing of your script to prevent it from running too quickly. For
example, if you’re sending a series of emails, you might want to introduce a short delay between each one to
avoid overloading the email server. In this case, you can use the sleep method to introduce a
delay between each email:

emails.each do |email|
  send_email(email)
  sleep(2)
end

In this example, we’re sending an email and then sleeping for 2 seconds before sending the next one.

Conclusion

The sleep method in Ruby is a useful tool to pause the execution of your script for a specified
amount of time. It can be used in various scenarios, such as waiting for an external resource or controlling the
pacing of your script. With its simple syntax and flexible duration options, sleep is a valuable
addition to any Ruby developer’s toolkit.