定时调度引擎 goroutine scheduler
背景
类似于 python schedule的伟大设计,实现golang版本的 golang scheduer模块
使用方式
package main
import (
"flag"
"fmt"
"time"
"github.com/kubeservice-stack/common/pkg/schedule"
)
func ExampleTask(name string) {
fmt.Println("Example Task " + name)
t := time.NewTicker(time.Millisecond * 100)
c := make(chan struct{})
time.AfterFunc(time.Second*3, func() {
close(c)
})
for {
select {
case <-t.C:
fmt.Println(".")
case <-c:
fmt.Println("")
return
}
}
}
type CustomLocker struct {
Data map[string]interface{} //对非携程安全的数据,安全添加和删除
}
func (c *CustomLocker) Lock(key string) (bool, error) {
c.Data[key] = time.Now()
return true, nil
}
func (c *CustomLocker) Unlock(key string) error {
delete(c.Data, key)
return nil
}
func main() {
var name string
flag.StringVar(&name, "task-name", "example", "The example task name. Default: example")
l := &CustomLocker{
Data: make(map[string]interface{}),
}
schedule.SetLocker(l)
schedule.Every(1).Second().Lock().Do(ExampleTask, name)
/*
schedule.Every(1).Second().Lock().Do(ExampleTask, name)
schedule.Every(2).Seconds().Lock().Do(ExampleTask, name)
schedule.Every(1).Minute().Lock().Do(ExampleTask, name)
schedule.Every(2).Minutes().Lock().Do(ExampleTask, name)
schedule.Every(1).Hour().Lock().Do(ExampleTask, name)
schedule.Every(2).Hours().Lock().Do(ExampleTask, name)
schedule.Every(1).Day().Lock().Do(ExampleTask, name)
schedule.Every(2).Days().Lock().Do(ExampleTask, name)
schedule.Every(1).Week().Lock().Do(ExampleTask, name)
schedule.Every(2).Weeks().Lock().Do(ExampleTask, name)
*/
<-schedule.Start()
}
其他调度方式
...
schedule.Every(1).At(now.Format("15:04:05")).DoSafely(fmt.Println, "aa")
schedule.Every(1).At(now.Format("15:04:05")).DoSafely(fmt.Println, "bb")
schedule.Week().At(now.Format("15:04:05")).Loc(time.UTC).Do(CallBackTest, "aaa")
<-schedule.Start()
...
「如果这篇文章对你有用,请随意打赏」
FEATURED TAGS
agent
apiserver
application
bandwidth-limit
cgo
cgroupfs
ci/cd
client-go
cloudnative
cncf
cni
community
container
container-network-interface
containerd
controller
coredns
crd
custom-controller
deployment
docker
docker-build
docker-image
drop
ebpf
ecology
egress
etcd
gitee
github
gitlab
golang
governance
hpa
http2
image
ingress
iptables
jobs
kata
kata-runtime
kernel
kind
kubelet
kubenetes
kubernetes
library
linux-os
logging
loki
metrics
monitor
namespace
network
network-troubleshooting
node
nodeport
pingmesh
pod
prestop
prometheus
proxyless
pvc
rollingupdate
schedule
scheduler
serverless
sidecar
sigtrem
systemd
throttling
timeout
tools
traceroute