先扔程式碼,之後寫思路
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 協議》,轉載必須註明作者和本文連結