timewheel

package module
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 23, 2023 License: MIT Imports: 5 Imported by: 1

README

timewheel

时间轮,是一种实现延迟功能(定时器)的巧妙算法,在 Netty,Zookeeper,Kafka 等各种框架中,甚至 Linux 内核中都有用到。

🎉 安装

go get -u -v github.com/itmisx/timewheel

✅ 使用
// 直接函数调用
{
	// 启动时间轮
	// 参数-func(interface{}),定时器过期回调函数,参数为AddTimer传入的值,类型为interface{}
	timewheel.Start(callback)
	// timerID,定时器id,用来删除定时器
	// 参数1-string,定时器id,相同的定时器id会覆盖旧的定时器
	// 参数2-time.Duration,定时器间隔
	// 参数3-interface{},定时器数据,将传递到回调函数
	timewheel.AddTimer("timerID", time.Second*3, "data")
	// 停止定时器
	// 参数-string,定时器的id
	timewheel.StopTimer("timerID")
	timewheel.Stop()
}

// 结构体方法调用
{
	// 参数1-time.Duration,时间轮精度
	// 参数2-int,时间槽数量
	// 参数3-func(interface{}),定时器过期回调函数
	tw := timewheel.New(time.Second, 60, callback)
	tw.Start()
	// timerID,定时器id,用来删除定时器
	// 参数1-string,定时器id,相同的定时器id会覆盖旧的定时器
	// 参数2-time.Duration,定时器间隔
	// 参数3-interface{},定时器数据,将传递到回调函数
	tw.AddTimer("timerID", time.Second*3, "data")
	tw.Stop()
}
Benchmark
goos: darwin
goarch: amd64
pkg: 192.168.1.75/go-pkg/timewheel
cpu: Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
BenchmarkTimeWheel-4   	 1000000	      1550 ns/op

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultSlotInterval = time.Second * 1
	DefaultSlotNum      = 60
)

Functions

func AddTimer

func AddTimer(key string, interval time.Duration, data interface{})

func Start

func Start(callback func(interface{}))

func Stop

func Stop()

func StopTimer

func StopTimer(key string)

Types

type TimeWheel

type TimeWheel struct {
	// contains filtered or unexported fields
}

func New

func New(slotDuration time.Duration, slotNum int, callback func(interface{})) *TimeWheel

New 实例化时间轮

func (*TimeWheel) AddTimer

func (tw *TimeWheel) AddTimer(timerID string, interval time.Duration, data interface{}) (success bool)

AddTimer add timer

func (*TimeWheel) Start

func (tw *TimeWheel) Start()

Start start timewheel

func (*TimeWheel) Stop

func (tw *TimeWheel) Stop() (success bool)

Stop stop the timewheel

func (*TimeWheel) StopTimer

func (tw *TimeWheel) StopTimer(timerID string) (success bool)

StopTimer stop timer

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL