Skip to content

Instantly share code, notes, and snippets.

@clsource
Last active February 2, 2024 14:59
Show Gist options
  • Save clsource/6c63dc5e68a555d1dbd4fc3d533c3dd1 to your computer and use it in GitHub Desktop.
Save clsource/6c63dc5e68a555d1dbd4fc3d533c3dd1 to your computer and use it in GitHub Desktop.
Go Exercise: Create a 5 minute Timer that displays the current remaining time in terminal
package main
import (
"fmt"
"sync/atomic"
"time"
)
type SecondsCounter struct {
count int32
}
func pad_number(number int32) string {
if number < 10 {
return fmt.Sprintf("0%d", number)
}
return fmt.Sprintf("%d", number)
}
func format_timer(seconds int32) string {
return fmt.Sprintf("%s:%s", pad_number((seconds%3600)/60), pad_number((seconds%3600)%60))
}
func print_timer(seconds *SecondsCounter) {
fmt.Println(format_timer(atomic.LoadInt32(&seconds.count)))
}
func add_to_timer(seconds *SecondsCounter, amount int32) {
atomic.AddInt32(&seconds.count, amount)
}
func main() {
ticker := time.NewTicker(1000 * time.Millisecond)
done := make(chan bool)
seconds := new(SecondsCounter)
add_to_timer(seconds, 300)
print_timer(seconds)
go func() {
for {
select {
case <-done:
return
case <-ticker.C:
add_to_timer(seconds, -1)
print_timer(seconds)
}
}
}()
time.Sleep(5 * time.Minute)
ticker.Stop()
done <- true
fmt.Println("Timer Done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment