go 实现定时任务

2021-06-09  本文已影响0人  我爱张智容

代码:

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {

    stopAll := make(chan bool)
    go func() {
        quit := make(chan os.Signal, 1)
        signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL)
        <-quit
        stopAll <- true
        fmt.Println("Shutting down server...")
    }()

    if err := run(stopAll); err != nil {
        fmt.Println(err)
    }
}

func run(stop <-chan bool) error {
    tick := time.NewTicker(10 * time.Millisecond)
    for {
        select {
        case <-stop:
            return nil
        case <-tick.C:
            process()
        }
    }
}

func process() {

    fmt.Println("=========== process ================")

}

上一篇 下一篇

猜你喜欢

热点阅读