-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcronjob.go
More file actions
58 lines (47 loc) · 1.08 KB
/
cronjob.go
File metadata and controls
58 lines (47 loc) · 1.08 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package cxcron
import (
"sync"
"time"
)
// CronJob runs the given function at the specified interval until stopped.
type CronJob struct {
interval time.Duration
stopChan chan struct{}
f func()
ticker *time.Ticker
wg sync.WaitGroup
}
// NewCronJob creates a new CronJob instance with the given interval and function.
func NewCronJob(interval time.Duration, f func()) *CronJob {
job := &CronJob{
interval: interval,
stopChan: make(chan struct{}),
f: f,
}
job.wg.Add(1)
go func() {
job.run()
}()
return job
}
// run starts the cron job.
func (job *CronJob) run() {
defer job.wg.Done()
// Call the function immediately before starting the ticker
job.f()
job.ticker = time.NewTicker(job.interval)
defer job.ticker.Stop()
for {
select {
case <-job.ticker.C:
job.f()
case <-job.stopChan:
return
}
}
}
// Stop stops the cron job from running.
func (job *CronJob) Stop() {
close(job.stopChan)
job.wg.Wait()
}