gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/sync/task/local/local.go (about) 1 // Package local provides a local task runner 2 package local 3 4 import ( 5 "fmt" 6 "sync" 7 8 "gitee.com/liuxuezhan/go-micro-v1.18.0/sync/task" 9 ) 10 11 type localTask struct { 12 opts task.Options 13 mtx sync.RWMutex 14 status string 15 } 16 17 func (l *localTask) Run(t task.Command) error { 18 ch := make(chan error, l.opts.Pool) 19 20 for i := 0; i < l.opts.Pool; i++ { 21 go func() { 22 ch <- t.Execute() 23 }() 24 } 25 26 var err error 27 28 for i := 0; i < l.opts.Pool; i++ { 29 er := <-ch 30 if err != nil { 31 err = er 32 l.mtx.Lock() 33 l.status = fmt.Sprintf("command [%s] status: %s", t.Name, err.Error()) 34 l.mtx.Unlock() 35 } 36 } 37 38 close(ch) 39 return err 40 } 41 42 func (l *localTask) Status() string { 43 l.mtx.RLock() 44 defer l.mtx.RUnlock() 45 return l.status 46 } 47 48 func NewTask(opts ...task.Option) task.Task { 49 var options task.Options 50 for _, o := range opts { 51 o(&options) 52 } 53 if options.Pool == 0 { 54 options.Pool = 1 55 } 56 return &localTask{ 57 opts: options, 58 } 59 }