task.go 887 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "math/rand"
  7. "time"
  8. )
  9. type Task struct {
  10. id int
  11. ctx context.Context
  12. cncl context.CancelFunc
  13. writer io.Writer
  14. }
  15. func NewTask(id int, ctx context.Context, writer io.Writer) *Task {
  16. nctx, cncl := context.WithCancel(ctx)
  17. t := &Task{
  18. id: id,
  19. ctx: nctx,
  20. cncl: cncl,
  21. writer: writer,
  22. }
  23. return t
  24. }
  25. func (t *Task) Task() error {
  26. tstr := time.Now().Format(time.RFC3339Nano)
  27. LabelLoop:
  28. for {
  29. _, _ = fmt.Fprintf(t.writer, "[Task %d] printing, time=%s.\n", t.id, tstr)
  30. jitter := rand.Int31n(1000)
  31. sltime := time.Duration(jitter+1000) * time.Millisecond
  32. time.Sleep(sltime)
  33. select {
  34. case <-t.ctx.Done():
  35. {
  36. break LabelLoop
  37. }
  38. default:
  39. continue LabelLoop
  40. }
  41. }
  42. _, _ = fmt.Fprintf(t.writer, "[Task %d] printing task end.\n", t.id)
  43. return nil
  44. }
  45. func (t *Task) Cancel(_ error) {
  46. t.cncl()
  47. }