github.com/benz9527/xboot@v0.0.0-20240504061247-c23f15593274/timer/x_sched.go (about)

     1  package timer
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/benz9527/xboot/lib/hrtime"
     7  )
     8  
     9  type xScheduler struct {
    10  	intervals    []time.Duration
    11  	currentIndex int
    12  	isFinite     bool
    13  }
    14  
    15  var (
    16  	_ Scheduler = (*xScheduler)(nil)
    17  )
    18  
    19  func NewFiniteScheduler(intervals ...time.Duration) Scheduler {
    20  	if len(intervals) == 0 {
    21  		return nil
    22  	}
    23  	for _, interval := range intervals {
    24  		if interval.Milliseconds() <= 0 {
    25  			return nil
    26  		}
    27  	}
    28  	return &xScheduler{
    29  		isFinite:     true,
    30  		intervals:    intervals,
    31  		currentIndex: 0,
    32  	}
    33  }
    34  
    35  func NewInfiniteScheduler(intervals ...time.Duration) Scheduler {
    36  	if len(intervals) == 0 {
    37  		return nil
    38  	}
    39  	for _, interval := range intervals {
    40  		if interval.Milliseconds() <= 0 {
    41  			return nil
    42  		}
    43  	}
    44  	return &xScheduler{
    45  		intervals:    intervals,
    46  		currentIndex: 0,
    47  	}
    48  }
    49  
    50  func (x *xScheduler) next(beginMs int64) (nextExpiredMs int64) {
    51  	beginTime := hrtime.MillisToDefaultTzTime(beginMs)
    52  	if beginTime.IsZero() || len(x.intervals) == 0 {
    53  		return -1
    54  	}
    55  
    56  	if x.currentIndex >= len(x.intervals) {
    57  		if x.isFinite {
    58  			return -1
    59  		}
    60  		x.currentIndex = 0
    61  	}
    62  	if x.intervals[x.currentIndex].Milliseconds() <= 0 {
    63  		return -1
    64  	}
    65  	next := beginTime.Add(x.intervals[x.currentIndex])
    66  	x.currentIndex++
    67  	return next.UnixMilli()
    68  }
    69  
    70  func (x *xScheduler) GetRestLoopCount() int64 {
    71  	if x.isFinite {
    72  		return int64(len(x.intervals) - x.currentIndex)
    73  	}
    74  	return -1
    75  }