Esempio n. 1
0
// NewWorker creates a new gearman worker with the specified name and job function.
func NewWorker(name string, fn JobFunc) *Worker {
	// Turn a JobFunc into gearmanWorker.JobFunc
	jobFunc := func(job gearmanWorker.Job) ([]byte, error) {
		castedJob := Job(job)
		return fn(castedJob)
	}
	w := gearmanWorker.New(gearmanWorker.OneByOne)

	w.ErrorHandler = func(e error) {
		// Try to reconnect if it is a disconnect error
		wdc, ok := e.(*gearmanWorker.WorkerDisconnectError)
		if ok {
			lg.InfoD("err-disconnected-and-reconnecting", logger.M{"name": name, "error": e.Error()})
			r := retrier.New(retrier.ExponentialBackoff(5, 200*time.Millisecond), nil)
			if rc_err := r.Run(wdc.Reconnect); rc_err != nil {
				lg.CriticalD("err-disconnected-fully", logger.M{"name": name, "error": rc_err.Error()})
				defaultErrorHandler(rc_err)
				return
			}
			lg.InfoD("gearman-reconnected", logger.M{"name": name})
		} else {
			defaultErrorHandler(e)
		}
	}
	worker := &Worker{
		fn:   jobFunc,
		name: name,
		w:    w,
	}
	return worker
}
Esempio n. 2
0
// NewWorker creates a new gearman worker with the specified name and job function.
func NewWorker(name string, fn JobFunc) *Worker {
	// Turn a JobFunc into gearmanWorker.JobFunc
	jobFunc := func(job gearmanWorker.Job) ([]byte, error) {
		castedJob := Job(job)
		return fn(castedJob)
	}
	w := gearmanWorker.New(gearmanWorker.OneByOne)
	w.ErrorHandler = func(e error) {
		log.Println(e)
		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)
				}
			}
		}
	}
	worker := &Worker{fn: jobFunc, name: name, w: w, sigtermHandler: defaultSigtermHandler}
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, syscall.SIGTERM)
	go func() {
		<-sigc
		worker.sigtermHandler(worker)
	}()
	return worker
}