diff --git a/.golangci.yml b/.golangci.yml index 743bfac..89a230b 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -163,6 +163,7 @@ linters-settings: - d any - data any - n any + - t time.Time - f func() - cb func() - t testing.T diff --git a/README.md b/README.md index 3f7f9a8..8a9473f 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ It can run a function at a given time, in a given duration, or repeatedly at a g ## Index - [type Task](<#Task>) - - [func After\(d time.Duration, task func\(\)\) \*Task](<#After>) + - [func After\(duration time.Duration, task func\(\)\) \*Task](<#After>) - [func At\(t time.Time, task func\(\)\) \*Task](<#At>) - [func Every\(interval time.Duration, task func\(\) bool\) \*Task](<#Every>) - [func \(s \*Task\) ExecutesIn\(\) time.Duration](<#Task.ExecutesIn>) @@ -102,7 +102,7 @@ type Task struct { ### func [After]() ```go -func After(d time.Duration, task func()) *Task +func After(duration time.Duration, task func()) *Task ``` After executes the task after the given duration. The function is non\-blocking. If you want to wait for the task to be executed, use the Task.Wait method. @@ -201,6 +201,7 @@ import ( func main() { task := schedule.Every(time.Second, func() bool { fmt.Println("1 second is over!") + return true // return false to stop the task }) diff --git a/examples_test.go b/examples_test.go index 1e2dba0..bc764b9 100644 --- a/examples_test.go +++ b/examples_test.go @@ -30,6 +30,7 @@ func ExampleAt() { func ExampleEvery() { task := schedule.Every(time.Second, func() bool { fmt.Println("1 second is over!") + return true // return false to stop the task }) diff --git a/schedule.go b/schedule.go index 635d29d..b332691 100644 --- a/schedule.go +++ b/schedule.go @@ -55,13 +55,13 @@ func (s *Task) Stop() { // After executes the task after the given duration. // The function is non-blocking. If you want to wait for the task to be executed, use the Task.Wait method. -func After(d time.Duration, task func()) *Task { +func After(duration time.Duration, task func()) *Task { scheduler := newTask() - scheduler.nextExecution = time.Now().Add(d) + scheduler.nextExecution = time.Now().Add(duration) go func() { select { - case <-time.After(d): + case <-time.After(duration): task() scheduler.Stop() case <-scheduler.stop: @@ -104,9 +104,12 @@ func Every(interval time.Duration, task func() bool) *Task { select { case <-ticker.C: task() + scheduler.nextExecution = time.Now().Add(interval) + case <-scheduler.stop: ticker.Stop() + return } }