first commit

This commit is contained in:
Blizzard
2026-02-27 13:54:01 +08:00
commit fc585fa4df
127 changed files with 18548 additions and 0 deletions
+64
View File
@@ -0,0 +1,64 @@
package async
import (
"context"
"runtime/debug"
"sundynix-go/global"
"sync"
"time"
"go.uber.org/zap"
)
type AsyncTask func(ctx context.Context)
type namedTask struct {
name string
fn AsyncTask
}
type TaskRunner struct {
mu sync.Mutex
tasks []namedTask
}
// Add 添加任务
func (tr *TaskRunner) Add(name string, task AsyncTask) {
if task == nil {
return
}
tr.mu.Lock()
defer tr.mu.Unlock()
tr.tasks = append(tr.tasks, namedTask{name: name, fn: task})
}
// RunAll 安全执行
func (tr *TaskRunner) RunAll() {
tr.mu.Lock()
todoTasks := tr.tasks
tr.tasks = nil
tr.mu.Unlock()
for _, task := range todoTasks {
t := task
go func() {
defer func() {
if r := recover(); r != nil {
// 使用全局 Zap 记录结构化日志
// 这里的 global.Logger 替换为你实际的全局变量名
global.Logger.Error("异步任务异常崩溃",
zap.String("task_name", t.name),
zap.Any("panic_info", r),
zap.String("stack", string(debug.Stack())),
)
}
}()
// 异步任务执行,设置独立的超时控制
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
t.fn(ctx)
}()
}
}