Skip to content

anantadwi13/workers

Repository files navigation

workers

GitHub Workflow Status godoc GitHub codecov

Golang Worker

Installation

go get github.com/anantadwi13/workers@latest

Example

package main

import (
	"context"
	"errors"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/anantadwi13/workers"
)

func main() {
	shutdownSign := make(chan os.Signal)
	signal.Notify(shutdownSign, syscall.SIGINT, syscall.SIGKILL)

	log.Println("creating a worker instance")
	worker, err := workers.NewWorkerPool(workers.WorkerPoolConfig{
		QueueSize:       1,
		WorkerSize:      2,
		ShutdownTimeout: 1 * time.Second,
	})
	if err != nil {
		log.Fatalln("error:", err)
	}

	log.Println("starting up the worker")
	err = worker.Start()
	if err != nil {
		log.Fatalln("error:", err)
	}

	// job scheduling
	go func(w workers.Worker) {
		for i := 0; true; i++ {
			log.Println(i, "scheduled")

			job := workers.NewJobSimple(func(ctx context.Context, jobId string, params ...interface{}) {
				select {
				case <-time.After(2 * time.Second):
					log.Println(params[0], "successfully done")
				case <-ctx.Done():
					log.Println(params[0], "context deadline")
				}
			}, i)

			err := w.Push(job)
			if err != nil {
				log.Println("error:", i, err)
				if errors.Is(err, workers.ErrWorkerNotRunning) {
					return
				}
			}

			time.Sleep(1 * time.Second)
		}
	}(worker)

	// wait shutdown signal
	<-shutdownSign

	log.Println("shutting down the worker")
	err = worker.Shutdown()
	if err != nil {
		panic(err)
	}
	log.Println("the worker is successfully stopped")
}