worker.go 873 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. }
  10. type Callback func(ctx context.Context, w *Worker)
  11. func New(f Callback) *Worker {
  12. ctx, cancel := context.WithCancel(context.Background())
  13. w := Worker{ctx: ctx, cancel: cancel, chDone: make(chan bool)}
  14. return (&w).doit(f)
  15. }
  16. func (this *Worker) doit(f func(ctx context.Context, w *Worker)) *Worker {
  17. go func() {
  18. for {
  19. select {
  20. case <-this.ctx.Done():
  21. this.chDone <- true
  22. return
  23. default:
  24. f(this.ctx, this)
  25. }
  26. }
  27. }()
  28. return this
  29. }
  30. func (this *Worker) Shutdown(ctx context.Context) error {
  31. ctxb := ctx
  32. if ctxb == nil {
  33. ctxb = context.Background()
  34. }
  35. this.cancel()
  36. select {
  37. case <-this.chDone:
  38. return nil
  39. case <-ctxb.Done():
  40. return ctxb.Err()
  41. }
  42. }
  43. func (this *Worker) Finish() {
  44. this.cancel()
  45. }