Skip to content

Commit e01ad50

Browse files
committed
make allowance for blocking or non-blocking executor calls to Start
1 parent 4188f12 commit e01ad50

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

main/main.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"fmt"
5+
"sync"
56
"time"
67

78
"github.com/gbenroscience/scheduled-executor/utils"
@@ -13,6 +14,9 @@ func timeStampMillis() int {
1314

1415
func main() {
1516

17+
var wg sync.WaitGroup
18+
wg.Add(2)
19+
1620
totalCount := 0
1721
const MAX_CYCLES = 10
1822

@@ -24,16 +28,21 @@ func main() {
2428
fmt.Printf("sc:---%d.%4stime is %d\n", totalCount, " ", timeStampMillis())
2529
if totalCount > MAX_CYCLES {
2630
sc.Close()
31+
wg.Done()
2732
}
28-
}, true)
33+
}, true, true)
2934

3035
totalCount1 := 0
3136
sc1.Start(func() {
3237
totalCount1++
3338
fmt.Printf("sc1:---%d.%4stime is %d\n", totalCount1, " ", timeStampMillis())
3439
if totalCount1 > MAX_CYCLES {
3540
sc1.Close()
41+
wg.Done()
3642
}
37-
}, true)
43+
}, true, false)
44+
45+
wg.Wait()
46+
fmt.Println("All tasks completed.")
3847

3948
}

utils/timedexecutor.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,13 @@ func NewTimedExecutor(initialDelay time.Duration, delay time.Duration) *Schedule
2424
}
2525
}
2626

27-
func (se *ScheduledExecutor) Start(task func(), runAsync bool) {
27+
// Start begins the execution of the task at the specified intervals.
28+
// If runAsync is true, the task will be executed in a separate goroutine.
29+
// If runAsync is false, the task will block the goroutine until it completes.
30+
// If startAsync is false, the executor will start asynchronously. So the caller can continue without waiting for the task to start.
31+
// If startAsync is false, the caller(of Start) will wait until the task starts executing.
32+
// The task will be stopped when the context is canceled.
33+
func (se *ScheduledExecutor) Start(task func(), runAsync bool, startAsync bool) {
2834
se.ctx, se.cancel = context.WithCancel(context.Background())
2935
se.sigs = make(chan os.Signal, 1)
3036
signal.Notify(se.sigs, syscall.SIGINT, syscall.SIGTERM)
@@ -61,7 +67,9 @@ func (se *ScheduledExecutor) Start(task func(), runAsync bool) {
6167
}
6268
}()
6369

64-
<-se.ctx.Done()
70+
if !startAsync {
71+
<-se.ctx.Done()
72+
}
6573
}
6674

6775
func (se *ScheduledExecutor) Close() {

0 commit comments

Comments
 (0)