gitee.com/h79/goutils@v1.22.10/common/scheduler/delay.go (about)

     1  package scheduler
     2  
     3  import (
     4  	"gitee.com/h79/goutils/common/cache"
     5  	"gitee.com/h79/goutils/common/option"
     6  	"time"
     7  )
     8  
     9  type Delay struct {
    10  	items *cache.Cache[int64, bool, int64, *Job]
    11  }
    12  
    13  func NewDelay() *Delay {
    14  	return &Delay{
    15  		items: cache.New[int64, bool, int64, *Job](true),
    16  	}
    17  }
    18  
    19  func (d *Delay) Add(job *Job) {
    20  	now := time.Now().Local().UnixMilli() + job.Delay.Milliseconds()
    21  	part, _, _ := d.items.Add(now, false, true)
    22  	if part != nil {
    23  		part.AddChild(now, job, true)
    24  	}
    25  }
    26  
    27  func (d *Delay) Check(pool *Pool) {
    28  	var now = time.Now().Local().UnixMilli()
    29  	d.items.Delete(func(key int64, c *cache.Part[bool, int64, *Job]) bool {
    30  		if c.Get() {
    31  			return true
    32  		}
    33  		if now < key {
    34  			return false
    35  		}
    36  		// 需要执行
    37  		c.Set(true)
    38  		c.ForeachChild(func(key int64, c *Job) {
    39  			c.Delay = 0
    40  			pool.executeJob(c)
    41  		})
    42  		return true
    43  	})
    44  }
    45  
    46  func (d *Delay) Exec(opts ...option.Option) {
    47  	d.items.Delete(func(key int64, c *cache.Part[bool, int64, *Job]) bool {
    48  		// 需要执行
    49  		c.Set(true)
    50  		c.ForeachChild(func(key int64, c *Job) {
    51  			c.Delay = 0
    52  			_, _ = c.Execute(opts...)
    53  		})
    54  		return true
    55  	})
    56  }