1
0
mirror of https://github.com/fumiama/slowdo.git synced 2026-06-12 12:30:27 +08:00

feat: add context

This commit is contained in:
源文雨
2024-10-01 15:50:01 +09:00
parent 8e5724aac1
commit bc474bd3fb

22
job.go
View File

@@ -5,27 +5,29 @@ import (
"time" "time"
) )
type Job[item any] struct { type Job[item, ctx any] struct {
maxmait time.Duration maxmait time.Duration
commit func([]item) context ctx
commit func(ctx, []item)
itemmu sync.Mutex itemmu sync.Mutex
items []item items []item
timer *time.Timer timer *time.Timer
} }
func NewJob[item any]( func NewJob[item, ctx any](
maxwait time.Duration, commit func([]item), maxwait time.Duration, context ctx, commit func(ctx, []item),
) (*Job[item], error) { ) (*Job[item, ctx], error) {
if maxwait <= time.Millisecond { if maxwait <= time.Millisecond {
return nil, ErrWaitTimeTooShort return nil, ErrWaitTimeTooShort
} }
return &Job[item]{ return &Job[item, ctx]{
maxmait: maxwait, maxmait: maxwait,
context: context,
commit: commit, commit: commit,
}, nil }, nil
} }
func (jb *Job[item]) Add(it item) { func (jb *Job[item, ctx]) Add(it item) {
jb.itemmu.Lock() jb.itemmu.Lock()
defer jb.itemmu.Unlock() defer jb.itemmu.Unlock()
if len(jb.items) == 0 { if len(jb.items) == 0 {
@@ -34,7 +36,7 @@ func (jb *Job[item]) Add(it item) {
jb.items = append(jb.items, it) jb.items = append(jb.items, it)
} }
func (jb *Job[item]) Commit() { func (jb *Job[item, ctx]) Commit() {
jb.itemmu.Lock() jb.itemmu.Lock()
if jb.timer != nil { if jb.timer != nil {
jb.timer.Stop() jb.timer.Stop()
@@ -48,10 +50,10 @@ func (jb *Job[item]) Commit() {
copy(itemscp, jb.items) copy(itemscp, jb.items)
jb.items = jb.items[:0] jb.items = jb.items[:0]
jb.itemmu.Unlock() jb.itemmu.Unlock()
jb.commit(itemscp) jb.commit(jb.context, itemscp)
} }
func (jb *Job[item]) collect() { func (jb *Job[item, ctx]) collect() {
jb.itemmu.Lock() jb.itemmu.Lock()
defer jb.itemmu.Unlock() defer jb.itemmu.Unlock()
jb.timer = time.AfterFunc(jb.maxmait, jb.Commit) jb.timer = time.AfterFunc(jb.maxmait, jb.Commit)