main.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "github.com/vladimirok5959/golang-worker/worker"
  7. )
  8. func main() {
  9. fmt.Printf("Start!\n")
  10. w1 := worker.New(func(ctx context.Context, w *worker.Worker, o *[]worker.Iface) {
  11. fmt.Printf("Worker #1 one tick\n")
  12. for i := 0; i < 1000; i++ {
  13. select {
  14. case <-ctx.Done():
  15. fmt.Printf("Worker #1 fine I will shutdown!\n")
  16. return
  17. default:
  18. time.Sleep(1 * time.Millisecond)
  19. }
  20. }
  21. }, nil)
  22. w2 := worker.New(func(ctx context.Context, w *worker.Worker, o *[]worker.Iface) {
  23. fmt.Printf("Worker #2 one tick\n")
  24. for i := 0; i < 1000; i++ {
  25. select {
  26. case <-ctx.Done():
  27. fmt.Printf("Worker #2 fine I will shutdown!\n")
  28. return
  29. default:
  30. time.Sleep(1 * time.Millisecond)
  31. }
  32. }
  33. }, nil)
  34. _ = worker.New(func(ctx context.Context, w *worker.Worker, o *[]worker.Iface) {
  35. fmt.Printf("Worker #3 one tick\n")
  36. time.Sleep(2 * time.Second)
  37. fmt.Printf("Worker #3 Exit\n")
  38. w.Shutdown(nil)
  39. }, nil)
  40. // Just wait for goroutines
  41. time.Sleep(3 * time.Second)
  42. // Shutdown first
  43. // Normally, it's must be used with context
  44. w1.Shutdown(nil)
  45. // Shutdown second
  46. // Normally, it's must be used with context
  47. if err := w2.Shutdown(nil); err != nil {
  48. fmt.Printf("Worker #2 shutdown error: %s\n", err.Error())
  49. }
  50. // Wait for third
  51. // Will be exited automatically
  52. time.Sleep(1 * time.Second)
  53. fmt.Printf("End!\n")
  54. }