1
0
Fork 0

Add example daemon

This commit is contained in:
Gregory Eremin 2015-10-14 03:34:59 +03:00
parent 98bbbf91f4
commit 650c9d1b9d
2 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,53 @@
package daemons
import (
"log"
"math/rand"
"time"
"github.com/localhots/uberdaemon"
)
// NumberPrinter is a daemon that prints numbers once in a while.
type NumberPrinter struct {
uberdaemon.BaseDaemon
}
// Startup sets up panic handler and starts enqueuing number printing jobs.
func (n *NumberPrinter) Startup() {
n.HandlePanics(func() {
log.Println("Oh, crap!")
})
go n.enqueue()
}
// Shutdown is empty due to the lack of cleanup.
func (n *NumberPrinter) Shutdown() {}
func (n *NumberPrinter) enqueue() {
for {
select {
case <-n.ShutdownRequested():
return
default:
}
// Generate a random number between 1000 and 9999 and print it
num := 1000 + rand.Intn(9000)
n.Process(n.makeActor(num))
// Sleep for a second or less
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
}
}
func (n *NumberPrinter) makeActor(num int) uberdaemon.Actor {
return func() {
if rand.Intn(20) == 0 {
panic("Noooooooooo!")
}
log.Println("NumberPrinter says", num)
}
}

36
example/main.go Normal file
View File

@ -0,0 +1,36 @@
package main
import (
"flag"
"io/ioutil"
"log"
"os"
"os/signal"
"syscall"
"github.com/localhots/uberdaemon"
"github.com/localhots/uberdaemon/example/daemons"
)
func main() {
var debug bool
flag.BoolVar(&debug, "v", false, "Verbose mode")
flag.Parse()
if !debug {
log.SetOutput(ioutil.Discard)
}
uberd := uberdaemon.New()
uberd.AddDaemon(&daemons.NumberPrinter{})
uberd.Start()
defer uberd.Stop()
sig := make(chan os.Signal)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
for s := range sig {
if s == os.Interrupt {
return
}
}
}