123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- package ticker
- import (
- "context"
- "fmt"
- "time"
- )
- var _ Ticker = (*ticker)(nil)
- type Ticker interface {
- worker()
- Process(fun any) error
- 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 any) error {
- f, ok := fun.(func())
- if !ok {
- return fmt.Errorf("fun is not func")
- }
- t.f = f
- go t.worker()
- return nil
- }
- func (t *ticker) Stop() {
- t.ticker.Stop()
- t.cancel()
- }
|