fix: 修复待机控制器的 context 使用和忙循环问题

- interval: 添加 Sleep 避免默认分支的忙循环(CPU 100%)
- cron: 使用 context.Background() 确保定时任务完整执行,不受外部取消影响
- wait_card: 使用 context.Background() 确保读卡器监听完整执行

这些修复确保了关键操作能够完整运行,同时避免 CPU 资源浪费。
This commit is contained in:
2026-04-08 14:25:56 +08:00
parent bee3b98798
commit e31fca22c8
3 changed files with 9 additions and 4 deletions

View File

@@ -10,11 +10,12 @@ import (
"game-driver/pkg/card_reader" "game-driver/pkg/card_reader"
"game-driver/pkg/channel" "game-driver/pkg/channel"
"game-driver/pkg/tts" "game-driver/pkg/tts"
"go.uber.org/zap"
"io/fs" "io/fs"
"os" "os"
"sync" "sync"
"time" "time"
"go.uber.org/zap"
) )
func WaitCard(ctx context.Context) leaf.HandlerFunc { func WaitCard(ctx context.Context) leaf.HandlerFunc {
@@ -79,13 +80,14 @@ func WaitCard(ctx context.Context) leaf.HandlerFunc {
defer cardInfo.Close() defer cardInfo.Close()
// 结束信号通道 // 结束信号通道
cc, cancel := context.WithCancel(context.TODO()) // 使用独立 context 确保读卡器监听完整执行,不受外部取消影响
c2, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
wait.Add(1) wait.Add(1)
go func() { go func() {
defer wait.Done() defer wait.Done()
reader.OnCardInfo(cc, func(info *card_reader.CardInfo) { reader.OnCardInfo(c2, func(info *card_reader.CardInfo) {
cardInfo.Send(info.ID) cardInfo.Send(info.ID)
}) })
}() }()

View File

@@ -65,7 +65,8 @@ func Cron(rootRules []cronrange.Rule, cron string, play func(c context.Context)
case r := <-a: case r := <-a:
if r { if r {
if ok := m.TryLock(); ok { if ok := m.TryLock(); ok {
ctx, cc := context.WithCancel(context.TODO()) // 使用独立 context 确保任务完整执行,不受外部取消影响
ctx, cc := context.WithCancel(context.Background())
cancel = cc cancel = cc
waitGroup.Add(1) waitGroup.Add(1)
go func() { go func() {

View File

@@ -28,6 +28,8 @@ func Interval(interval int64, play func(c context.Context) error) func(c context
case <-c.Done(): case <-c.Done():
return nil return nil
default: default:
// 避免忙循环,短暂休眠
time.Sleep(10 * time.Millisecond)
} }
} }
} }