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

先扔代码,之后写思路

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("主协程终止")

}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
51
粉丝
16
喜欢
57
收藏
43
排名:519
访问:1.6 万
私信
所有博文
社区赞助商