How to create a countdown timer in Ruby
Creating the script
Shown below is the timer.rb file with the following code:
Code explanation
Line 1: We define a
clear_screenfunction that calls thesystem('clear')orsystem('cls')method depending on the operating system to clear the screen’s output after every second so that only one line is shown on the screen at any time.Line 9: The main logic of the countdown timer is in the
countdown_timerfunction. Here, we create awhileloop that repeatedly decrements the timer count until it reaches 0.Lines 10–11: The
divmodfunction returns the quotient and remainder when thesecondsvariable is divided by3600. Since one hour contains 3600 seconds, the quotient of the division will be the number of hours present inseconds. Theremainderis then also divided by60using thedivmodfunction to get the number of minutes and seconds in theremainder.Line 12: We use the
hours,mins, andsecsto create a formatted string,timeformat. This will display time in a timer format,HH:MM:SS, whereHHrepresents the number of hours,MMrepresents the number of minutes andSSrepresents the number of seconds. The%02dis used to format thehours,mins, andsecsto two digits.Lines 14–15: We print the timer count to the screen as soon as the
timeformatstring is ready. We use thesleepfunction with an argument of1to simulate the flow of time. After every second, thetimeformatstring will be updated to display the updated timer count.Lines 16–18: After one second, the
secondsvariable is decremented by 1 to calculate the hours, minutes, and seconds in the remaining timer count. Theclear_screenfunction is used to clear the screen output so that only one line shows the timer count on the screen.Line 21: Finally, we print a string to the screen after the timer count reaches 0 to indicate the timer has expired.
Line 27: We call the
countdowntimer and pass the number of seconds as an argument to start the timer from that time.
Conclusion
In this answer, we just print a statement after the timer expires, but there are many possibilities, such as calling a backup script that will start a backup of data after a certain time or calling the shutdown script to shut down a system after a certain period of user inactivity.
Free Resources