gearman-go/example/worker/worker.go

75 lines
1.8 KiB
Go
Raw Normal View History

2011-05-18 20:24:59 +08:00
package main
import (
2013-12-24 14:35:33 +08:00
"github.com/mikespook/gearman-go/worker"
"github.com/mikespook/golib/signal"
"log"
"os"
"strings"
"time"
2014-03-03 15:23:46 +08:00
"net"
2011-05-18 20:24:59 +08:00
)
2013-12-20 15:24:22 +08:00
func ToUpper(job worker.Job) ([]byte, error) {
2013-12-24 14:35:33 +08:00
log.Printf("ToUpper: Data=[%s]\n", job.Data())
data := []byte(strings.ToUpper(string(job.Data())))
return data, nil
2011-05-18 20:24:59 +08:00
}
2013-12-20 15:24:22 +08:00
func ToUpperDelay10(job worker.Job) ([]byte, error) {
2013-12-24 14:35:33 +08:00
log.Printf("ToUpper: Data=[%s]\n", job.Data())
time.Sleep(10 * time.Second)
data := []byte(strings.ToUpper(string(job.Data())))
return data, nil
2012-08-30 17:56:10 +08:00
}
2014-01-09 17:58:02 +08:00
func Foobar(job worker.Job) ([]byte, error) {
log.Printf("Foobar: Data=[%s]\n", job.Data())
for i := 0; i < 10; i++ {
job.SendWarning([]byte{byte(i)})
job.SendData([]byte{byte(i)})
job.UpdateStatus(i+1, 100)
}
return job.Data(), nil
}
2011-05-18 20:24:59 +08:00
func main() {
2013-12-24 14:35:33 +08:00
log.Println("Starting ...")
defer log.Println("Shutdown complete!")
w := worker.New(worker.Unlimited)
defer w.Close()
2013-12-20 15:24:22 +08:00
w.ErrorHandler = func(e error) {
2013-12-24 14:35:33 +08:00
log.Println(e)
2014-03-03 15:23:46 +08:00
if opErr, ok := e.(*net.OpError); ok {
if ! opErr.Temporary() {
proc, err := os.FindProcess(os.Getpid())
if err != nil {
log.Println(err)
}
if err := proc.Signal(os.Interrupt); err != nil {
log.Println(err)
}
2013-12-24 14:35:33 +08:00
}
}
}
w.JobHandler = func(job worker.Job) error {
log.Printf("Data=%s\n", job.Data())
return nil
}
w.AddServer("tcp4", "127.0.0.1:4730")
2014-01-09 17:58:02 +08:00
w.AddFunc("Foobar", Foobar, worker.Unlimited)
w.AddFunc("ToUpper", ToUpper, worker.Unlimited)
2013-12-24 14:39:04 +08:00
w.AddFunc("ToUpperTimeOut5", ToUpperDelay10, 5)
w.AddFunc("ToUpperTimeOut20", ToUpperDelay10, 20)
2014-01-09 17:58:02 +08:00
w.AddFunc("SysInfo", worker.SysInfo, worker.Unlimited)
w.AddFunc("MemInfo", worker.MemInfo, worker.Unlimited)
2013-12-24 14:35:33 +08:00
if err := w.Ready(); err != nil {
log.Fatal(err)
return
}
go w.Work()
sh := signal.NewHandler()
sh.Bind(os.Interrupt, func() bool { return true })
sh.Loop()
2011-05-18 20:24:59 +08:00
}