File size: 476 Bytes
7107f0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package cron

import "time"

type Cron struct {
	d  time.Duration
	ch chan struct{}
}

func NewCron(d time.Duration) *Cron {
	return &Cron{
		d:  d,
		ch: make(chan struct{}),
	}
}

func (c *Cron) Do(f func()) {
	go func() {
		ticker := time.NewTicker(c.d)
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
				f()
			case <-c.ch:
				return
			}
		}
	}()
}

func (c *Cron) Stop() {
	select {
	case _, _ = <-c.ch:
	default:
		c.ch <- struct{}{}
		close(c.ch)
	}
}