worker.go 688 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package worker
  2. import (
  3. "context"
  4. "log"
  5. "github.com/google/uuid"
  6. )
  7. type Job interface {
  8. ID() uuid.UUID
  9. Run() error
  10. }
  11. type Worker struct {
  12. WorkerPool chan chan Job
  13. JobChannel chan Job
  14. ctx context.Context
  15. }
  16. func NewWorker(ctx context.Context, workerPool chan chan Job) Worker {
  17. return Worker{
  18. WorkerPool: workerPool,
  19. JobChannel: make(chan Job),
  20. ctx: ctx,
  21. }
  22. }
  23. func (w Worker) Start() {
  24. go func() {
  25. for {
  26. w.WorkerPool <- w.JobChannel
  27. select {
  28. case job := <-w.JobChannel:
  29. if err := job.Run(); err != nil {
  30. log.Default().Printf("error running job %s: %s", job.ID(), err.Error())
  31. }
  32. case <-w.ctx.Done():
  33. return
  34. }
  35. }
  36. }()
  37. }