comparison bot/timer.go @ 10:5c124578fed2

fix timer bug
author Dennis C. M. <dennis@denniscm.com>
date Sat, 15 Mar 2025 17:03:53 +0000
parents
children aaf85ae1f942
comparison
equal deleted inserted replaced
9:228ab74e8321 10:5c124578fed2
1 package bot
2
3 import (
4 "fmt"
5 "log"
6 "os"
7 "time"
8 )
9
10 var quit chan struct{}
11
12 func startTimer(seconds int) {
13 if quit != nil {
14 close(quit)
15 }
16
17 quit = make(chan struct{})
18
19 go func() {
20 filename := "F:/Media/Twitch/Bot/timer.txt"
21 file, err := os.Create(filename)
22
23 if err != nil {
24 log.Fatal(err)
25 }
26
27 defer file.Close()
28 countdown := time.Duration(seconds) * time.Second
29 ticker := time.NewTicker(time.Second)
30 defer ticker.Stop()
31
32 log.Printf("bot: timer started with duration %d seconds", seconds)
33
34 for countdown >= 0 {
35 select {
36 case <-ticker.C:
37 totalSeconds := int(countdown.Seconds())
38 minutes := totalSeconds / 60
39 seconds := totalSeconds % 60
40 countdownMsg := fmt.Sprintf("%02d:%02d", minutes, seconds)
41
42 file.Seek(0, 0)
43 _, err = file.WriteString("")
44
45 if err != nil {
46 log.Fatal(err)
47 }
48
49 _, err = file.WriteString(countdownMsg)
50
51 if err != nil {
52 log.Fatal(err)
53 }
54
55 log.Printf("bot: timer updated to %s", countdownMsg)
56
57 countdown -= time.Second
58 case <-quit:
59 log.Println("bot: timer stopped")
60
61 return
62 }
63 }
64 }()
65 }