Golang之 golang common goroutine scheduler 定时调度引擎

Golang 通用基础库: goroutine scheduler 定时调度引擎

Posted by 董江 on Wednesday, May 31, 2023

定时调度引擎 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()
...	

「如果这篇文章对你有用,请随意打赏」

Kubeservice博客

如果这篇文章对你有用,请随意打赏

使用微信扫描二维码完成支付