testobject.go 795 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. type TestObject struct {
  8. ctx context.Context
  9. cancel context.CancelFunc
  10. chDone chan bool
  11. }
  12. func Run() *TestObject {
  13. ctx, cancel := context.WithCancel(context.Background())
  14. w := &TestObject{ctx: ctx, cancel: cancel, chDone: make(chan bool)}
  15. go func() {
  16. for {
  17. select {
  18. case <-w.ctx.Done():
  19. w.chDone <- true
  20. return
  21. case <-time.After(1 * time.Second):
  22. fmt.Printf("[TestObject]: I do something every second!\n")
  23. fmt.Printf("[TestObject]: Press CTRL + C for shutdown...\n")
  24. }
  25. }
  26. }()
  27. return w
  28. }
  29. func (t *TestObject) Shutdown(ctx context.Context) error {
  30. fmt.Printf("[TestObject]: OK! I will shutdown!\n")
  31. t.cancel()
  32. select {
  33. case <-t.chDone:
  34. return nil
  35. case <-ctx.Done():
  36. return ctx.Err()
  37. }
  38. }