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

46 lines
1.0 KiB
Go
Raw Normal View History

2015-10-14 00:34:59 +00:00
package daemons
import (
"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() {
2015-10-18 00:22:07 +00:00
n.HandlePanics(func(err interface{}) {
2015-10-24 16:25:16 +00:00
n.Logf("Oh, crap! There was a panic, take a look: %v", err)
2015-10-14 00:34:59 +00:00
})
2015-10-24 00:07:47 +00:00
n.LimitRate(3, time.Second)
2015-10-18 00:22:07 +00:00
n.SystemProcess("Random Number Generator", n.generateNumbers)
2015-10-14 00:34:59 +00:00
}
func (n *NumberPrinter) generateNumbers() {
2015-10-15 23:27:03 +00:00
for n.Continue() {
if rand.Intn(10) == 0 {
panic("Number generator refuses to work right now!")
}
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))
}
}
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() {
n.Log("Number printer says:", num)
2015-10-15 23:27:03 +00:00
// Making it crash sometimes
if num%10 == 0 {
panic("Nooooo! Random number generator returned a multiple of ten!")
2015-10-14 00:34:59 +00:00
}
}
}