fix(web,agent): P1 正确性与鉴权加固,P2 抽 fsutil 并补测试(v1.2.8)
This commit is contained in:
@@ -2,6 +2,7 @@ package scheduler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -15,8 +16,17 @@ type Scheduler struct {
|
||||
jobs []Job
|
||||
}
|
||||
|
||||
// New 会丢掉间隔非正的任务:time.NewTicker 对非正间隔直接 panic,这类任务应由调用方单独启动。
|
||||
func New(jobs ...Job) *Scheduler {
|
||||
return &Scheduler{jobs: jobs}
|
||||
valid := make([]Job, 0, len(jobs))
|
||||
for _, job := range jobs {
|
||||
if job.Interval <= 0 {
|
||||
log.Printf("scheduler: 任务 %s 间隔为 %v,已跳过", job.Name, job.Interval)
|
||||
continue
|
||||
}
|
||||
valid = append(valid, job)
|
||||
}
|
||||
return &Scheduler{jobs: valid}
|
||||
}
|
||||
|
||||
func (s *Scheduler) Start(ctx context.Context) {
|
||||
@@ -28,13 +38,22 @@ func (s *Scheduler) Start(ctx context.Context) {
|
||||
func (s *Scheduler) runJob(ctx context.Context, job Job) {
|
||||
ticker := time.NewTicker(job.Interval)
|
||||
defer ticker.Stop()
|
||||
job.Run(ctx)
|
||||
// 单个任务 panic 不能带走整个进程:包一层 recover,记录后继续下一轮
|
||||
run := func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("scheduler: 任务 %s panic: %v", job.Name, r)
|
||||
}
|
||||
}()
|
||||
job.Run(ctx)
|
||||
}
|
||||
run()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
job.Run(ctx)
|
||||
run()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package scheduler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestNewSkipsNonPositiveIntervals:time.NewTicker 对非正间隔会 panic,这类任务必须在建表时丢掉。
|
||||
func TestNewSkipsNonPositiveIntervals(t *testing.T) {
|
||||
s := New(
|
||||
Job{Name: "zero", Interval: 0, Run: func(context.Context) {}},
|
||||
Job{Name: "negative", Interval: -time.Second, Run: func(context.Context) {}},
|
||||
Job{Name: "ok", Interval: time.Hour, Run: func(context.Context) {}},
|
||||
)
|
||||
if len(s.jobs) != 1 || s.jobs[0].Name != "ok" {
|
||||
t.Fatalf("非正间隔的任务应被跳过,实际保留 %d 个", len(s.jobs))
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunJobRecoversFromPanic:单个任务 panic 不能带走整个进程,且要能继续下一轮。
|
||||
func TestRunJobRecoversFromPanic(t *testing.T) {
|
||||
var calls int32
|
||||
s := New(Job{Name: "panic", Interval: 5 * time.Millisecond, Run: func(context.Context) {
|
||||
atomic.AddInt32(&calls, 1)
|
||||
panic("boom")
|
||||
}})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
s.Start(ctx)
|
||||
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) && atomic.LoadInt32(&calls) < 3 {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if got := atomic.LoadInt32(&calls); got < 3 {
|
||||
t.Fatalf("panic 后应继续后续轮次,实际只执行了 %d 次", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user