github.com/go-eden/common@v0.1.15-0.20210617133546-059099253264/etime/etime_interval.go (about)

     1  package etime
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/go-eden/common/esync"
     6  	"runtime/debug"
     7  	"time"
     8  )
     9  
    10  type Interval struct {
    11  	closed   esync.AtomicBool
    12  	f        func()
    13  	timer    *time.Timer
    14  	duration time.Duration
    15  }
    16  
    17  func NewInterval(d time.Duration, f func()) *Interval {
    18  	t := &Interval{
    19  		duration: d,
    20  		f:        f,
    21  	}
    22  	t.timer = time.AfterFunc(time.Hour, t.exec)
    23  	t.timer.Reset(d)
    24  	return t
    25  }
    26  
    27  func (t *Interval) exec() {
    28  	defer func() {
    29  		if e := recover(); e != nil {
    30  			fmt.Println("interval timer-func panic: \n" + string(debug.Stack()))
    31  		}
    32  		if !t.closed.Get() {
    33  			t.timer.Reset(t.duration)
    34  		}
    35  	}()
    36  	if !t.closed.Get() {
    37  		t.f()
    38  	}
    39  }
    40  
    41  func (t *Interval) Close() {
    42  	if t.closed.Swap(true) == false {
    43  		t.timer.Stop()
    44  	}
    45  }