voucher/internal/server/cron.go

75 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package server
import (
"context"
"fmt"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/transport"
"github.com/robfig/cron"
"voucher/internal/conf"
"voucher/internal/service"
)
var _ transport.Server = (*CronServer)(nil)
type CronServer struct {
conf *conf.Bootstrap
cron *cron.Cron
VoucherService *service.VoucherService
}
func NewCronServer(
conf *conf.Bootstrap,
cron *cron.Cron,
VoucherService *service.VoucherService,
) *CronServer {
return &CronServer{
conf: conf,
cron: cron,
VoucherService: VoucherService,
}
}
// Start .
// 每五秒: */5 * * * * ?
// 每隔1分钟执行一次"0 */1 * * * ?"
// 每天23点执行一次"0 0 23 * * ?"
// 每天凌晨1点执行一次"0 0 1 * * ?"
// 每月1号凌晨1点执行一次"0 0 1 1 * ?"
// 在26分、29分、33分执行一次"0 26,29,33 * * * ?"
// 每天的0点、13点、18点、21点都执行一次"0 0 0,13,18,21 * * ?"
func (cs *CronServer) Start(ctx context.Context) error {
if !cs.conf.Cron.IsOpen {
fmt.Printf("cron 未开启...")
return nil
}
if err := cs.VoucherService.CronOrderNotice(ctx); err != nil {
log.Error("cron order notice Start err: %v", err)
return err
}
if err := cs.VoucherService.CronWarningBudget(ctx); err != nil {
log.Error("cron warning budget Start err: %v", err)
return err
}
cs.cron.Start()
return nil
}
func (cs *CronServer) Stop(_ context.Context) error {
if !cs.conf.Cron.IsOpen {
return nil
}
fmt.Printf("cron 关闭中...")
cs.cron.Stop()
return nil
}