Menu
Coddy logo textTech

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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create 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:

  1. Parse the first input by splitting on commas to get individual meditation steps
  2. For each step, split on colons to extract the instruction and duration (in seconds)
  3. Convert the duration strings to integers using the strconv package
  4. Convert the second input to an integer to get the number of cycles
  5. Display the session header: "=== MEDITATION TIMER ==="
  6. Display the session setup: "Starting meditation session with [number_of_cycles] cycles"
  7. For each cycle (starting from cycle 1):
    • Display: "--- Cycle [cycle_number] ---"
    • For each meditation step:
      • Display: "[instruction]..."
      • Use time.Sleep to pause for the specified duration (convert seconds to time.Duration by multiplying by time.Second)
      • After the sleep, display: "[instruction] complete ([duration] seconds)"
    • After completing all steps in a cycle, display: "Cycle [cycle_number] finished"
  8. 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)
  9. 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
	
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow