关于使用 go cron 库(任务调度)平滑关闭的实现

Golang
503
0
0
2022-07-23

先扔代码,之后写思路

package main

import (
    "fmt" 
    "github.com/robfig/cron/v3" 
    "os" 
    "os/signal" 
    "sync" 
    "time"
)

var needStop = false
var needStopL = &sync.Mutex{}

func stop() {
    needStopL.Lock()
    defer needStopL.Unlock()
    needStop = true
}

func getStop() bool {
    needStopL.Lock()
    defer needStopL.Unlock()
    return needStop
}

func heart() {
    for {
        fmt.Println("HEART_IN_RUN_JOB :", time.Now())
        time.Sleep(time.Second * 5)

        if getStop() {
            fmt.Println("接收到终止信号,当前任务结束")
            return
        }
    }
}

var c = cron.New()

func main() {
    fmt.Println("hello")

    _, err := c.AddFunc("* * * * *", heart)
    if err != nil {
        fmt.Println(err)
    }
    go c.Run()

    quit := make(chan os.Signal)
    signal.Notify(quit, os.Interrupt)
    // 这一句是 go chan 等待接受值,只是把接到的值直接扔掉了,此处是主协程的阻塞处
    <-quit

    fmt.Println("开始停止")

    ctx := c.Stop()
    stop()
    <-ctx.Done()

    fmt.Println("主协程终止")

}