feat: 个人中心发布
This commit is contained in:
+39
-13
@@ -2,37 +2,63 @@ package async
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime/debug"
|
||||
"sundynix-go/global"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// AsyncTask 定义了异步任务的函数原型
|
||||
type AsyncTask func(ctx context.Context)
|
||||
|
||||
// TaskRunner 任务收集器
|
||||
type namedTask struct {
|
||||
name string
|
||||
fn AsyncTask
|
||||
}
|
||||
|
||||
type TaskRunner struct {
|
||||
tasks []AsyncTask
|
||||
mu sync.Mutex
|
||||
tasks []namedTask
|
||||
}
|
||||
|
||||
// Add 添加一个任务到队列中
|
||||
func (tr *TaskRunner) Add(task AsyncTask) {
|
||||
tr.tasks = append(tr.tasks, task)
|
||||
// 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 安全地启动所有任务
|
||||
// RunAll 安全执行
|
||||
func (tr *TaskRunner) RunAll() {
|
||||
for _, task := range tr.tasks {
|
||||
t := task // 避免闭包变量捕获问题
|
||||
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 {
|
||||
global.Logger.Info("[AsyncError] 任务执行崩溃", zap.Any("recover", r))
|
||||
// 使用全局 Zap 记录结构化日志
|
||||
// 这里的 global.Logger 替换为你实际的全局变量名
|
||||
global.Logger.Error("异步任务异常崩溃",
|
||||
zap.String("task_name", t.name),
|
||||
zap.Any("panic_info", r),
|
||||
zap.String("stack", string(debug.Stack())),
|
||||
)
|
||||
}
|
||||
}()
|
||||
// 异步任务通常使用 Background,避免受主请求超时影响
|
||||
// 也可以自定义一个更长的超时 context
|
||||
t(context.Background())
|
||||
|
||||
// 异步任务执行,设置独立的超时控制
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
t.fn(ctx)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user