-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.go
43 lines (40 loc) · 1.02 KB
/
tasks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
* @Date: 2022-04-30 15:53:54
* @LastEditTime: 2022-05-01 22:54:24
* @FilePath: \go-frame\internal\components\tasks\tasks.go
*/
package tasks
import (
"context"
"github.com/depost2024/go-frame/internal/adapter/log"
"github.com/depost2024/go-frame/pkgs/logs"
"github.com/go-logr/zapr"
"github.com/robfig/cron/v3"
"go.uber.org/fx"
"go.uber.org/zap"
)
func New(zapLog *zap.Logger, lc fx.Lifecycle) *cron.Cron {
cron := cron.New(cron.WithSeconds(), cron.WithChain(cron.Recover(zapr.NewLogger(zapLog))), cron.WithLogger(cron.VerbosePrintfLogger(log.CronLog{Logger: zapLog})))
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
cron.Start()
logs.Info("定时任务启动成功")
return nil
},
OnStop: func(ctx context.Context) error {
cronCtx := cron.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-cronCtx.Done():
err := cronCtx.Err()
if err != context.Canceled {
return err
}
logs.Info("定时任务已关闭...")
return nil
}
},
})
return cron
}