Skip to content

Instantly share code, notes, and snippets.

@clsource
Last active February 2, 2024 14:59

Revisions

  1. clsource created this gist Feb 2, 2024.
    57 changes: 57 additions & 0 deletions timer.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    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")
    }