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() {
|
2015-10-18 00:22:07 +00:00
|
|
|
n.HandlePanics(func(err interface{}) {
|
|
|
|
log.Printf("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
|
|
|
}
|
|
|
|
|
|
|
|
// Shutdown is empty due to the lack of cleanup.
|
|
|
|
func (n *NumberPrinter) Shutdown() {}
|
|
|
|
|
2015-10-17 01:51:05 +00:00
|
|
|
func (n *NumberPrinter) generateNumbers() {
|
2015-10-15 23:27:03 +00:00
|
|
|
for n.Continue() {
|
2015-10-17 01:51:05 +00:00
|
|
|
if rand.Intn(7) == 0 {
|
|
|
|
panic("Number generator don't work on Sundays!")
|
|
|
|
}
|
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() {
|
2015-10-15 23:27:03 +00:00
|
|
|
// Making it crash sometimes
|
2015-10-17 01:51:05 +00:00
|
|
|
if rand.Intn(10) == 0 {
|
|
|
|
panic("Nooooo! Random number generator returned a zero!")
|
2015-10-14 00:34:59 +00:00
|
|
|
}
|
|
|
|
|
2015-10-17 01:51:05 +00:00
|
|
|
log.Println("Number printer says:", num)
|
2015-10-14 00:34:59 +00:00
|
|
|
}
|
|
|
|
}
|