Skip to content

Instantly share code, notes, and snippets.

@vxcute
Created February 4, 2023 14:20
Show Gist options
  • Save vxcute/e356a5e7c3ca6581914d94ba39795ae4 to your computer and use it in GitHub Desktop.
Save vxcute/e356a5e7c3ca6581914d94ba39795ae4 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
type SCHEDULED_ROUTINE func()
type Schedular struct {
routine SCHEDULED_ROUTINE
interval time.Duration
quit chan struct{}
}
func NewSchedular(routine SCHEDULED_ROUTINE, interval time.Duration) *Schedular {
return &Schedular{ routine: routine, interval: interval, quit: make(chan struct{}) }
}
func (s *Schedular) Run() {
ticker := time.NewTicker(s.interval)
go func() {
for {
select {
case <- ticker.C:
s.routine()
case <- s.quit:
ticker.Stop()
return
}
}
}()
}
func (s *Schedular) Quit() {
s.quit <- struct{}{}
}
func hello() {
fmt.Println("Hello, World !")
}
func waitForInterrupt() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<- c
}
func main() {
s := NewSchedular(hello, time.Second * 1)
s.Run()
time.Sleep(time.Second * 5)
s.Quit()
waitForInterrupt()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment