1
0
Fork 0
shezmu/example/daemons/number_printer.go

49 lines
984 B
Go
Raw Normal View History

2015-10-14 00:34:59 +00:00
package daemons
import (
"log"
"math/rand"
"time"
2015-10-14 00:50:43 +00:00
"github.com/localhots/satan"
2015-10-14 00:34:59 +00:00
)
// NumberPrinter is a daemon that prints numbers once in a while.
type NumberPrinter struct {
2015-10-14 00:50:43 +00:00
satan.BaseDaemon
2015-10-14 00:34:59 +00:00
}
// Startup sets up panic handler and starts enqueuing number printing jobs.
func (n *NumberPrinter) Startup() {
n.HandlePanics(func() {
log.Println("Oh, crap!")
})
2015-10-15 23:27:03 +00:00
n.SystemProcess(n.enqueue)
2015-10-14 00:34:59 +00:00
}
// Shutdown is empty due to the lack of cleanup.
func (n *NumberPrinter) Shutdown() {}
func (n *NumberPrinter) enqueue() {
2015-10-15 23:27:03 +00:00
for n.Continue() {
2015-10-14 00:34:59 +00:00
// 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)
}
}
2015-10-14 00:50:43 +00:00
func (n *NumberPrinter) makeActor(num int) satan.Actor {
2015-10-14 00:34:59 +00:00
return func() {
2015-10-15 23:27:03 +00:00
// Making it crash sometimes
2015-10-14 00:34:59 +00:00
if rand.Intn(20) == 0 {
panic("Noooooooooo!")
}
log.Println("NumberPrinter says", num)
}
}