first commit
This commit is contained in:
		
							
								
								
									
										52
									
								
								pkg/ticker/ticker.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										52
									
								
								pkg/ticker/ticker.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,52 @@
 | 
			
		||||
package ticker
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"context"
 | 
			
		||||
	"time"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
var _ Ticker = (*ticker)(nil)
 | 
			
		||||
 | 
			
		||||
type Ticker interface {
 | 
			
		||||
	worker()
 | 
			
		||||
 | 
			
		||||
	Process(fun func())
 | 
			
		||||
	Stop()
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type ticker struct {
 | 
			
		||||
	ticker *time.Ticker
 | 
			
		||||
	ctx    context.Context
 | 
			
		||||
	cancel context.CancelFunc
 | 
			
		||||
	f      func()
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func New(d time.Duration) Ticker {
 | 
			
		||||
	ctx, cancelFunc := context.WithCancel(context.Background())
 | 
			
		||||
	return &ticker{
 | 
			
		||||
		ticker: time.NewTicker(d),
 | 
			
		||||
		ctx:    ctx,
 | 
			
		||||
		cancel: cancelFunc,
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (t *ticker) worker() {
 | 
			
		||||
	for {
 | 
			
		||||
		select {
 | 
			
		||||
		case <-t.ticker.C:
 | 
			
		||||
			t.f()
 | 
			
		||||
		case <-t.ctx.Done():
 | 
			
		||||
			return
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (t *ticker) Process(fun func()) {
 | 
			
		||||
	t.f = fun
 | 
			
		||||
	go t.worker()
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (t *ticker) Stop() {
 | 
			
		||||
	t.ticker.Stop()
 | 
			
		||||
	t.cancel()
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user