Files
sundynix-plant-be/utils/async/async_task.go
T
2026-02-13 10:51:08 +08:00

39 lines
847 B
Go

package async
import (
"context"
"sundynix-go/global"
"go.uber.org/zap"
)
// AsyncTask 定义了异步任务的函数原型
type AsyncTask func(ctx context.Context)
// TaskRunner 任务收集器
type TaskRunner struct {
tasks []AsyncTask
}
// Add 添加一个任务到队列中
func (tr *TaskRunner) Add(task AsyncTask) {
tr.tasks = append(tr.tasks, task)
}
// RunAll 安全地启动所有任务
func (tr *TaskRunner) RunAll() {
for _, task := range tr.tasks {
t := task // 避免闭包变量捕获问题
go func() {
defer func() {
if r := recover(); r != nil {
global.Logger.Info("[AsyncError] 任务执行崩溃", zap.Any("recover", r))
}
}()
// 异步任务通常使用 Background,避免受主请求超时影响
// 也可以自定义一个更长的超时 context
t(context.Background())
}()
}
}