github.com/ngicks/gokugen@v0.0.5/example/simple/main.go (about) 1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "github.com/ngicks/gokugen/scheduler" 9 ) 10 11 func main() { 12 if err := _main(); err != nil { 13 panic(err) 14 } 15 } 16 17 func printNowWithDelay(id int, delay time.Duration) func(ctx context.Context, scheduled time.Time) { 18 return func(ctx context.Context, scheduled time.Time) { 19 now := time.Now() 20 var isCtxCancelled bool 21 if delay > 0 { 22 timer := time.NewTimer(delay) 23 select { 24 case <-timer.C: 25 case <-ctx.Done(): 26 } 27 } 28 select { 29 case <-ctx.Done(): 30 isCtxCancelled = true 31 default: 32 } 33 34 fmt.Printf( 35 "id: %d, scheduled: %s, diff to now: %s, isCtxCancelled: %t\n", 36 id, 37 scheduled.Format(time.RFC3339Nano), 38 now.Sub(scheduled).String(), 39 isCtxCancelled, 40 ) 41 } 42 } 43 44 func _main() error { 45 sched := scheduler.NewScheduler(5, 0) 46 47 now := time.Now() 48 printNow := func(id int) func(ctx context.Context, scheduled time.Time) { 49 return printNowWithDelay(id, 0) 50 } 51 52 sched.Schedule(scheduler.NewTask(now, printNow(0))) 53 sched.Schedule(scheduler.NewTask(now.Add(time.Second), printNow(1))) 54 sched.Schedule(scheduler.NewTask(now.Add(time.Second+500*time.Millisecond), printNow(2))) 55 sched.Schedule(scheduler.NewTask(now.Add(2*time.Second+500*time.Millisecond), printNow(3))) 56 sched.Schedule(scheduler.NewTask(now.Add(3*time.Second+time.Millisecond), printNow(4))) 57 sched.Schedule(scheduler.NewTask(now.Add(4*time.Second+500*time.Millisecond), printNow(5))) 58 t, _ := sched.Schedule(scheduler.NewTask(now.Add(4*time.Second+600*time.Millisecond), printNow(6))) 59 go func() { 60 time.Sleep(4*time.Second + 550*time.Millisecond) 61 t.Cancel() 62 }() 63 sched.Schedule(scheduler.NewTask(now.Add(5*time.Second), printNowWithDelay(7, time.Second))) 64 sched.Schedule(scheduler.NewTask(now.Add(5*time.Second+time.Nanosecond), printNowWithDelay(8, time.Second))) 65 sched.Schedule(scheduler.NewTask(now.Add(5*time.Second+2*time.Nanosecond), printNowWithDelay(9, time.Second))) 66 sched.Schedule(scheduler.NewTask(now.Add(5*time.Second+3*time.Nanosecond), printNowWithDelay(10, time.Second))) 67 sched.Schedule(scheduler.NewTask(now.Add(5*time.Second+4*time.Nanosecond), printNowWithDelay(11, time.Second))) 68 // These 2 task are delayed because the scheduler limits concurrently processed tasks to 5. 69 sched.Schedule(scheduler.NewTask(now.Add(5*time.Second+5*time.Nanosecond), printNowWithDelay(12, time.Second))) 70 sched.Schedule(scheduler.NewTask(now.Add(5*time.Second+6*time.Nanosecond), printNowWithDelay(13, time.Second))) 71 72 sched.Schedule(scheduler.NewTask(now.Add(8*time.Second), printNowWithDelay(14, time.Second))) 73 74 ctx, cancel := context.WithDeadline(context.Background(), now.Add(8*time.Second)) 75 defer func() { 76 fmt.Println("calling cancel") 77 cancel() 78 }() 79 err := sched.Start(ctx) 80 fmt.Println("Start returned") 81 sched.End() 82 return err 83 }