github.com/haraldrudell/parl@v0.4.176/ptime/alert.go (about)

     1  /*
     2  © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package ptime
     7  
     8  import "time"
     9  
    10  // Alert impelments a renewable alert timer. not thread-safe
    11  type Alert struct {
    12  	time.Duration
    13  	// Timer.C can be awaited for any trigging of the timer
    14  	//	- Timer.C never closes and only sends a single value on trig
    15  	//	- Timer is reinitialized on each Start invocation
    16  	*time.Timer
    17  	// Fired may be set to true by consumer on Timer.C trig
    18  	//	- doing so saves a [time.Timer.Stop] invocation on next [Alert.Stop]
    19  	// true if the timer trigged after the last Start invocation prior to any Stop invocation
    20  	Fired bool
    21  }
    22  
    23  // NewAlert allocates a renewable alert time of specific duration
    24  //   - [Alert.Start] initializes a new period regardless of state
    25  //   - [Alert.Stop] releases resources regardless of state. [Alert.Stop] is idempotent
    26  //   - if [Alert.Start] was invoked, a subsequent [Alert.Stop] is required to release resources
    27  //   - after Start, [Alert.Timer.C] can be awaited for any trigging of the timer
    28  //   - [Alert.Timer.C] never closes and only sends a single value on trig
    29  //   - [Alert.Fired] is true if Start was invoked and the timer trigged prior to Stop
    30  func NewAlert(d time.Duration) (al *Alert) {
    31  	al = &Alert{Duration: d}
    32  	return
    33  }
    34  
    35  // Start initializes a new alert period
    36  //   - can be invoked at any time. Not thread-safe
    37  func (al *Alert) Start() {
    38  	if al.Timer != nil && !al.Fired {
    39  		al.Timer.Stop()
    40  	}
    41  	al.Timer = time.NewTimer(al.Duration)
    42  	al.Fired = false
    43  }
    44  
    45  // Stop releases resources associated with this alert
    46  //   - idempotent, can be invoked at any time. Not thread-safe
    47  func (al *Alert) Stop() {
    48  	if al.Timer != nil && !al.Fired {
    49  		al.Timer.Stop()
    50  	}
    51  	al.Timer = nil
    52  }