Last active
February 21, 2022 03:02
-
-
Save nathanblair/54f3e991b1bd6789d6b4a33be0153941 to your computer and use it in GitHub Desktop.
Create an interruptible, scheduled event loop in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"log" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
// registers a channel for handling an program kill/interrupt signal | |
func RegisterInterruptHandler() (interrupt chan os.Signal) { | |
interrupt = make(chan os.Signal) | |
signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM) | |
return | |
} | |
// creates a periodic ticker | |
func registerTicker(frequencyTime int) (ticker *time.Ticker) { | |
return time.NewTicker(time.Duration(frequencyTime) * time.Second) | |
} | |
func run() { | |
// Run your service code here | |
} | |
func main() { | |
outlog := log.New(os.Stdout, "", log.LstdFlags) | |
errlog := log.New(os.Stderr, "[ERROR] ", log.LstdFlags) | |
outlog.Printf("Spinning up service...") | |
interrupt := lib.RegisterInterruptHandler() | |
ticker := lib.RegisterTicker(updateFrequency) | |
outlog.Printf("Service registered! Starting...") | |
interrupted := false | |
for !interrupted { | |
select { | |
case <-ticker.C: | |
lib.Run() | |
case s := <-interrupt: | |
outlog.Printf("Service stop requested: %v\n", s) | |
interrupted = true | |
} | |
} | |
defer ticker.Stop() | |
defer close(interrupt) | |
outlog.Printf("Service stopped!\n") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment