package main
import (
"fmt"
"log"
"time"
"github.com/jasonlvhit/gocron"
"github.com/robfig/cron"
)
func task() {
fmt.Println("I am runnning task.", time.Now())
}
func superWang() {
fmt.Println("I am runnning superWang.", time.Now())
}
//每隔4秒执行一次(cron定时器)
func mineOne() {
i := 0
c := cron.New()
spec := "0/4 * * * * ? "
c.AddFunc(spec, func() {
i++
log.Println("execute per second", i)
})
c.Start()
}
func scheduler2() {
//每隔1秒执行一个任务,每隔4秒执行另一个任务
s := gocron.NewScheduler()
s.Every(1).Seconds().Do(task)
s.Every(4).Seconds().Do(superWang)
sc := s.Start() // keep the channel
go scheduler(s, sc) // wait
<-sc // it will happens if the channel is closed
}
//8秒后删除task任务,16秒后删除所有任务
func scheduler(s *gocron.Scheduler, sc chan bool) {
time.Sleep(8 * time.Second)
s.Remove(task) //remove task
time.Sleep(8 * time.Second)
s.Clear()
fmt.Println("All task removed")
close(sc) // close the channel
}
func main() {
//cron定时器
go mineOne()
//延迟和间隔定时器
go scheduler2()
select {}
}