worker.go 878 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package worker
  2. import (
  3. "log"
  4. "time"
  5. "github.com/google/uuid"
  6. )
  7. type Job interface {
  8. ID() string
  9. EnqueueTime() time.Time
  10. Run() error
  11. SetData([]byte)
  12. }
  13. type Worker struct {
  14. exitChan chan bool
  15. uuid uuid.UUID
  16. WorkerPool chan chan Job
  17. JobChannel chan Job
  18. }
  19. func NewWorker(uuid uuid.UUID, workerPool chan chan Job) *Worker {
  20. return &Worker{
  21. exitChan: make(chan bool),
  22. uuid: uuid,
  23. WorkerPool: workerPool,
  24. JobChannel: make(chan Job),
  25. }
  26. }
  27. func (w *Worker) Start() {
  28. go func() {
  29. for {
  30. w.WorkerPool <- w.JobChannel
  31. select {
  32. case job := <-w.JobChannel:
  33. if err := job.Run(); err != nil {
  34. log.Default().Printf("error running job %s: %s", job.ID(), err.Error())
  35. }
  36. case <-w.exitChan:
  37. log.Default().Printf("quitting worker with UUID: %v", w.uuid)
  38. return
  39. }
  40. }
  41. }()
  42. }
  43. func (w *Worker) Stop() {
  44. w.exitChan <- true
  45. }