12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- package main
- import (
- "context"
- "fmt"
- "io"
- "math/rand"
- "time"
- )
- type Task struct {
- id int
- ctx context.Context
- cncl context.CancelFunc
- writer io.Writer
- }
- func NewTask(id int, ctx context.Context, writer io.Writer) *Task {
- nctx, cncl := context.WithCancel(ctx)
- t := &Task{
- id: id,
- ctx: nctx,
- cncl: cncl,
- writer: writer,
- }
- return t
- }
- func (t *Task) Task() error {
- tstr := time.Now().Format(time.RFC3339Nano)
- LabelLoop:
- for {
- _, _ = fmt.Fprintf(t.writer, "[Task %d] printing, time=%s.\n", t.id, tstr)
- jitter := rand.Int31n(1000)
- sltime := time.Duration(jitter+1000) * time.Millisecond
- time.Sleep(sltime)
- select {
- case <-t.ctx.Done():
- {
- break LabelLoop
- }
- default:
- continue LabelLoop
- }
- }
- _, _ = fmt.Fprintf(t.writer, "[Task %d] printing task end.\n", t.id)
- return nil
- }
- func (t *Task) Cancel(_ error) {
- t.cncl()
- }
|