tq

package module
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2021 License: MIT Imports: 2 Imported by: 2

README

tq(time queue):时间任务队列

​ 如你所见,此任务队列使用channel实现,仅使用Golang 官方包synctime实现了所有功能;优点不言自明。本队列误差不会累积、且并发安全

快速开始

参考

工作原理

​ 几乎在同一时间依次Add time.Duration1s 2s 3s 8s 12s 5s 7s 4s 13s的任务,那么taskChans中将有3个任务管道用来存储任务:

任务管道1 id: 0      任务: 1s 2s 3s 8s 12s 13s
任务管道2 id: 1      任务:5s 7s
任务管道3 id: 2      任务:4s

每个任务管道有一个对应的协程,执行响应的任务。所以,顺序添加任务是最优的;逆序添加任务是最差的,等效于使用time.After。

注意

​ 队列存在的误差大小与系统相关;由time.Sleep()的延时的误差导致,测试发现time.Sleep()实际延时时长总是大于设定时长,因此任务总是稍有延迟执行。

var a []time.Duration = make([]time.Duration, 0, 20)
for i := 0; i < 20; i++ {
	s := time.Now()
	time.Sleep(time.Nanosecond)

	a = append(a, time.Since(s))
    // time.Sleep(time.Millisecond * 200)
}
var t time.Duration
for _, v := range a {
	fmt.Println(v)
	t = t + v
}
fmt.Println("平均误差:", t/20)

​ 系统上的误差可以通过以上代码大致了解,在Windows系统上误差较大,平均误差甚至可以达到10ms级别(似乎和CPU频率有关,低压U误差更大)。

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type TQ

type TQ struct {

	// 达到任务执行时间时返回对应的Ts.P; 请使用for-range及时读取, 否则会阻塞以致影响后续任务
	MQ chan interface{}
	// MQ阻塞告警,当len(MQ)*3 > cap(MQ)时为True
	Block bool
	// contains filtered or unexported fields
}

func NewTQ added in v0.2.2

func NewTQ() *TQ

NewTQ

@ioOut: 被丢弃任务输出日志;对于MQ中未被及时读取的的数据,唯一的操作是将其丢弃,但避免静默处理,因此需要打日志

func (*TQ) Add

func (t *TQ) Add(r Ts) error

Add 增加任务

当MQ被阻塞时,Add会被主动阻塞

func (*TQ) Drop added in v0.3.0

func (t *TQ) Drop()

Drop 销毁

type Ts

type Ts struct {
	T time.Time   // 设定执行时间
	P interface{} // 执行时MQ返回的数据
}

Ts 表示一个任务

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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