Fix: timer
This commit is contained in:
		| @@ -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)) | ||||
| 			} | ||||
| 		} | ||||
| 	}() | ||||
|   | ||||
		Reference in New Issue
	
	Block a user
	 Grail Finder
					Grail Finder