Sleeping and Tickers
Part of the Logic & Flow section of Coddy's GO journey — lesson 64 of 68.
Sometimes you need to control the timing of your program's execution. Go provides two essential functions in the time package for this: time.Sleep for pausing execution and time.NewTicker for performing actions at regular intervals.
The time.Sleep function pauses your program for a specified duration. It takes a time.Duration as its parameter and blocks execution until that time has passed:
fmt.Println("Starting...")
time.Sleep(2 * time.Second)
fmt.Println("Two seconds have passed!")For repeated actions at regular intervals, time.NewTicker creates a ticker that sends values on a channel at specified intervals. This is useful for tasks that need to run periodically:
ticker := time.NewTicker(1 * time.Second)
for i := 0; i < 3; i++ {
<-ticker.C // Wait for the next tick
fmt.Println("Tick", i+1)
}These timing functions are essential for creating delays, implementing timeouts, and scheduling recurring operations in your Go programs.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a meditation session timer that uses time.Sleep to create pauses between guided instructions and demonstrates the basic timing control in Go programs.
You will receive two inputs:
- A string containing meditation steps in the format
"step1:duration,step2:duration,step3:duration"(e.g.,"Breathe in:3,Hold:2,Breathe out:4") - A string containing the number of cycles to repeat (e.g.,
"5")
Your task is to:
- Parse the first input by splitting on commas to get individual meditation steps
- For each step, split on colons to extract the instruction and duration (in seconds)
- Convert the duration strings to integers using the
strconvpackage - Convert the second input to an integer to get the number of cycles
- Display the session header:
"=== MEDITATION TIMER ===" - Display the session setup:
"Starting meditation session with [number_of_cycles] cycles" - For each cycle (starting from cycle 1):
- Display:
"--- Cycle [cycle_number] ---" - For each meditation step:
- Display:
"[instruction]..." - Use
time.Sleepto pause for the specified duration (convert seconds totime.Durationby multiplying bytime.Second) - After the sleep, display:
"[instruction] complete ([duration] seconds)"
- Display:
- After completing all steps in a cycle, display:
"Cycle [cycle_number] finished"
- Display:
- After all cycles are complete, display session summary:
"=== SESSION COMPLETE ===""Total cycles completed: [number_of_cycles]""Steps per cycle: [number_of_steps]""Total meditation time: [total_seconds] seconds"(sum of all step durations multiplied by number of cycles)
- Display the completion message:
"Meditation session finished - well done!"
Use the time package for sleep operations, the strings package to split input strings, the strconv package to convert strings to integers, and the fmt package for output. Remember that time.Sleep takes a time.Duration parameter, so you need to multiply your integer seconds by time.Second to create the proper duration value. This challenge demonstrates how to use time.Sleep to create timed pauses in program execution for practical applications like guided meditation or exercise timers.
Cheat sheet
Use time.Sleep to pause program execution for a specified duration:
time.Sleep(2 * time.Second)Use time.NewTicker to perform actions at regular intervals:
ticker := time.NewTicker(1 * time.Second)
for i := 0; i < 3; i++ {
<-ticker.C // Wait for the next tick
fmt.Println("Tick", i+1)
}Both functions use time.Duration values. Convert integers to duration by multiplying by time.Second.
Try it yourself
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"time"
)
func main() {
// Read input using bufio.Scanner to handle spaces properly
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
stepsInput := scanner.Text()
scanner.Scan()
cyclesInput := scanner.Text()
// Parse the meditation steps and cycles
steps := strings.Split(stepsInput, ",")
cycles, _ := strconv.Atoi(cyclesInput)
// TODO: Write your code below
// Parse each step to extract instruction and duration
// Remember to check if parts slice has enough elements before accessing
// Display session header and setup
// Loop through cycles and steps
// Use time.Sleep for pauses (consider using milliseconds for testing)
// Display completion messages and summary
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task7Error Handling In-Depth
Custom Error TypesWrapping Errors with `%w`Unwrapping with `errors.Is`Unwrapping with `errors.As`Understanding `panic`Using `recover`Recap - Safe Division10Working with Time
Getting the Current TimeCreating a Specific TimeFormatting TimeParsing Time StringsTime DurationTime ArithmeticSleeping and TickersRecap - Simple Timer2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors