timing

package
v0.0.0-...-817968b Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2021 License: Apache-2.0 Imports: 6 Imported by: 0

README

timing

高效的定时器管理,与官方的timer区别

  • 实现算法:这里采用Hierarchical Time Wheel,官方采用小顶堆
  • 调度方式:这里只有1个协程管理定时器,1个协程执行过期回调
  • 执行方式:这里采用callback的方式,官方采用channel的方式

使用方式

func TestTimer(t *testing.T) {
	fmt.Printf("start %+v\n", time.Now())

	timing.NewDelayer(time.Second*2, func(data interface{}) {
		fmt.Printf("delay %+v, 2\n", time.Now())
	}, nil)

	timing.NewDelayer(time.Second*4, func(data interface{}) {
		fmt.Printf("delay %+v, 4\n", time.Now())
	}, nil)

	i := 0
	timing.NewTicker(time.Second, func(data interface{}) {
		i++
		fmt.Printf("tick  %+v, %+v\n", time.Now(), i)
	}, nil)

	time.Sleep(time.Second * 10)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetDefault

func SetDefault(e Engine)

SetDefault 设置默认engine

func Stop

func Stop(timerID uint64)

Stop 关闭定时器

Types

type Callback

type Callback func(data interface{})

Callback 回调函数,data 为传入附加参数,如果不需要额外参数可以传nil

type Config

type Config struct {
	Precision int64       // 执行精度,单位毫秒,默认为1
	Exec      Executor    // 执行器,默认单独协程中执行过期timer
	Clock     clock.Clock // 用于获取当前时间,默认clock.New()
	WheelNum  int         // 默认wheel个数,默认为3
}

type Engine

type Engine interface {
	// 当前时间戳
	Now() int64
	// 启动定时器
	Start(timer Timer) bool
	// 关闭定时器
	Stop(timer Timer) bool
	// 关闭Engine
	Close() error
}

Engine 毫秒级定时器管理

func NewEngine

func NewEngine(conf *Config) Engine

NewEngine 创建新Engine

type Executor

type Executor interface {
	Post(t []Timer)
	Close() error
}

Executor timer执行器,默认单独线程中执行

func NewExecutor

func NewExecutor() Executor

NewExecutor 默认调度器

type ID

type ID = uint64

ID 定时器唯一ID,自增且非零

func NewDelayer

func NewDelayer(delay time.Duration, cb Callback, data interface{}, opts ...Option) ID

NewDelayer 创建timer,delay为延迟时间

func NewTicker

func NewTicker(d time.Duration, cb Callback, data interface{}, opts ...Option) ID

NewTicker 启动定时器,多次执行,本次执行完后会重新注册

func NewTimer

func NewTimer(expired time.Time, cb Callback, data interface{}, opts ...Option) ID

NewTimer 根据过期时间创建定时器,如果需要再次重置,需要先关闭原timer,再创建新timer

type Option

type Option func(o *Options)

func WithEngine

func WithEngine(e Engine) Option

type Options

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

Options 创建Timer可选参数

type Timer

type Timer interface {
	// ID 全局唯一ID,非零自增
	ID() ID
	// Stop 停止timer or ticker
	Stop()
	// contains filtered or unexported methods
}

Timer 定时器

Timer不能Reset,只能Stop后重新创建新Timer,Timer释放后会放到Pool中复用
使用时用户持有ID,而非Timer指针,使用更加安全,但会有一点额外的性能损耗

Jump to

Keyboard shortcuts

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