Fix: timer

This commit is contained in:
Grail Finder
2025-07-04 21:35:59 +03:00
parent 0e2baa1a0f
commit 3af3657c7a
2 changed files with 12 additions and 10 deletions

View File

@ -337,7 +337,7 @@ func HandleGiveClue(w http.ResponseWriter, r *http.Request) {
fi.Room.ThisTurnLimit = 9
}
fi.Room.OpenedThisTurn = 0
StartTurnTimer(fi.Room.ID, time.Duration(fi.Room.Settings.RoundTime)*time.Second)
StartTurnTimer(fi.Room.ID, fi.Room.Settings.RoundTime)
log.Debug("given clue", "clue", clue, "limit", fi.Room.ThisTurnLimit)
notify(models.NotifyBacklogPrefix+fi.Room.ID, clue+num)
notifyBotIfNeeded(fi.Room)

View File

@ -2,7 +2,9 @@ package handlers
import (
"context"
"fmt"
"gralias/models"
"log/slog"
"strconv"
"sync"
"time"
@ -18,29 +20,29 @@ var (
mu sync.Mutex
)
func StartTurnTimer(roomID string, duration time.Duration) {
func StartTurnTimer(roomID string, timeLeft uint32) {
mu.Lock()
defer mu.Unlock()
if _, exists := timers[roomID]; exists {
slog.Debug("trying to launch already running timer", "room_id", roomID)
return // Timer already running
}
ticker := time.NewTicker(1 * time.Second)
done := make(chan bool)
timers[roomID] = &roomTimer{ticker: ticker, done: done}
go func() {
room, err := repo.RoomGetByID(context.Background(), roomID)
if err != nil {
log.Error("failed to get room by id", "error", err)
StopTurnTimer(roomID)
return
}
timeLeft := room.Settings.RoundTime
for {
select {
case <-done:
return
case <-ticker.C:
if timeLeft <= 0 {
room, err := repo.RoomGetByID(context.Background(), roomID)
if err != nil {
log.Error("failed to get room by id", "error", err)
StopTurnTimer(roomID)
return
}
log.Info("turn time is over", "room_id", roomID)
room.ChangeTurn()
room.MimeDone = false
@ -53,7 +55,7 @@ func StartTurnTimer(roomID string, duration time.Duration) {
return
}
timeLeft--
notify(models.NotifyRoomUpdatePrefix+roomID, "")
notify(models.NotifyTurnTimerPrefix+roomID, fmt.Sprintf("%d", timeLeft))
}
}
}()