Skip to content

Commit 015224e

Browse files
committed
update CronFunc
1 parent dc4c6d6 commit 015224e

File tree

2 files changed

+16
-14
lines changed

2 files changed

+16
-14
lines changed

timer/example_test.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,15 @@ func ExampleCronExpr() {
4646
func ExampleCron() {
4747
d := timer.NewDispatcher(10)
4848

49+
// cron expr
50+
cronExpr, err := timer.NewCronExpr("* * * * * *")
51+
if err != nil {
52+
return
53+
}
54+
4955
// cron
5056
var c *timer.Cron
51-
c, _ = d.CronFunc("* * * * * *", func() {
57+
c = d.CronFunc(cronExpr, func() {
5258
fmt.Println("My name is Leaf")
5359
c.Stop()
5460
})

timer/timer.go

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package timer
22

33
import (
4-
"errors"
54
"github.com/name5566/leaf/conf"
65
"github.com/name5566/leaf/log"
76
"runtime"
@@ -64,23 +63,20 @@ type Cron struct {
6463
}
6564

6665
func (c *Cron) Stop() {
67-
c.t.Stop()
66+
if c.t != nil {
67+
c.t.Stop()
68+
}
6869
}
6970

70-
func (disp *Dispatcher) CronFunc(expr string, _cb func()) (*Cron, error) {
71-
cronExpr, err := NewCronExpr(expr)
72-
if err != nil {
73-
return nil, err
74-
}
71+
func (disp *Dispatcher) CronFunc(cronExpr *CronExpr, _cb func()) *Cron {
72+
c := new(Cron)
7573

7674
now := time.Now()
7775
nextTime := cronExpr.Next(now)
7876
if nextTime.IsZero() {
79-
return nil, errors.New("next time not found")
77+
return c
8078
}
8179

82-
cron := new(Cron)
83-
8480
// callback
8581
var cb func()
8682
cb = func() {
@@ -91,9 +87,9 @@ func (disp *Dispatcher) CronFunc(expr string, _cb func()) (*Cron, error) {
9187
if nextTime.IsZero() {
9288
return
9389
}
94-
cron.t = disp.AfterFunc(nextTime.Sub(now), cb)
90+
c.t = disp.AfterFunc(nextTime.Sub(now), cb)
9591
}
9692

97-
cron.t = disp.AfterFunc(nextTime.Sub(now), cb)
98-
return cron, nil
93+
c.t = disp.AfterFunc(nextTime.Sub(now), cb)
94+
return c
9995
}

0 commit comments

Comments
 (0)