worker.go 937 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package worker
  2. import (
  3. "context"
  4. )
  5. type Worker struct {
  6. ctx context.Context
  7. cancel context.CancelFunc
  8. chDone chan bool
  9. stopped bool
  10. }
  11. type Iface interface{}
  12. type Callback func(ctx context.Context, w *Worker, o *[]Iface)
  13. func New(f Callback, o *[]Iface) *Worker {
  14. ctx, cancel := context.WithCancel(context.Background())
  15. w := Worker{ctx: ctx, cancel: cancel, chDone: make(chan bool)}
  16. return (&w).loop(f, o)
  17. }
  18. func (this *Worker) loop(f Callback, o *[]Iface) *Worker {
  19. go func() {
  20. for {
  21. select {
  22. case <-this.ctx.Done():
  23. this.chDone <- true
  24. return
  25. default:
  26. f(this.ctx, this, o)
  27. }
  28. }
  29. }()
  30. return this
  31. }
  32. func (this *Worker) Shutdown(ctx context.Context) error {
  33. if this.stopped {
  34. return nil
  35. }
  36. this.stopped = true
  37. ctxb := ctx
  38. if ctxb == nil {
  39. ctxb = context.Background()
  40. }
  41. this.cancel()
  42. select {
  43. case <-this.chDone:
  44. return nil
  45. case <-ctxb.Done():
  46. return ctxb.Err()
  47. }
  48. }