Skip to content
鼓励作者:欢迎打赏犒劳

go定时任务

真实项目中的使用场景

go
package main

import (
	"context"
	"log"
	"runtime/debug"
	"time"
)

const (
	monitorRiskStatusJobInterval = 3 * time.Second
)

func MonitorJobInit() {
	// 启动时立即执行一次
	go func() {
		ctx := context.WithValue(context.Background(), "logid", "123456")
		defer func() {
			if err := recover(); err != nil {
				log.Printf("MonitorJobInit panic err: %v, stack = %v", err, string(debug.Stack()))
			}
		}()
		log.Printf("MonitorJobInit - Initial run on startup...")
		BeginExecHandler(ctx)
		log.Printf("MonitorJobInit - Initial run completed.")
	}()

	// 在 goroutine 内部 defer,确保退出时释放资源
	go func() {
		ctx := context.WithValue(context.Background(), "logid", "123456")
		// 启动定时循环:首次延迟后开始周期执行
		ticker := time.NewTicker(monitorRiskStatusJobInterval)
		defer func() {
			ticker.Stop()
			if err := recover(); err != nil {
				log.Printf("MonitorJobInit panic err: %v, stack = %v", err, string(debug.Stack()))
			}
		}()
		for {
			select {
			case <-ticker.C:
				log.Printf("MonitorJobInit start ...")
				BeginExecHandler(ctx)
				log.Printf("MonitorJobInit end ...")
			}
		}
	}()
}

func BeginExecHandler(ctx context.Context) {
	log.Printf("MonitorJobInit begin exec handler...")
}
func main() {
	MonitorJobInit()
	select {}
}

如有转载或 CV 的请标注本站原文地址