1
0
mirror of https://github.com/go-task/task.git synced 2025-06-10 23:57:30 +02:00

Cancel and restart long running process on file change by using context.WithCancel(..)

Closes #59
This commit is contained in:
Jack Mordaunt 2017-08-04 23:48:15 +08:00 committed by Andrey Nering
parent a2c96e9cdd
commit ddd063f29e

View File

@ -13,12 +13,22 @@ import (
func (e *Executor) watchTasks(args ...string) error { func (e *Executor) watchTasks(args ...string) error {
e.printfln("task: Started watching for tasks: %s", strings.Join(args, ", ")) e.printfln("task: Started watching for tasks: %s", strings.Join(args, ", "))
// run tasks on init var isCtxErr = func(err error) bool {
for _, a := range args { switch err {
if err := e.RunTask(context.Background(), Call{Task: a}); err != nil { case context.Canceled, context.DeadlineExceeded:
e.println(err) return true
break
} }
return false
}
ctx, cancel := context.WithCancel(context.Background())
for _, a := range args {
a := a
go func() {
if err := e.RunTask(ctx, Call{Task: a}); err != nil && !isCtxErr(err) {
e.println(err)
}
}()
} }
watcher, err := fsnotify.NewWatcher() watcher, err := fsnotify.NewWatcher()
@ -36,19 +46,21 @@ func (e *Executor) watchTasks(args ...string) error {
} }
}() }()
loop:
for { for {
select { select {
case <-watcher.Events: case <-watcher.Events:
cancel()
ctx, cancel = context.WithCancel(context.Background())
for _, a := range args { for _, a := range args {
if err := e.RunTask(context.Background(), Call{Task: a}); err != nil { a := a
go func() {
if err := e.RunTask(ctx, Call{Task: a}); err != nil && !isCtxErr(err) {
e.println(err) e.println(err)
continue loop
} }
}()
} }
case err := <-watcher.Errors: case err := <-watcher.Errors:
e.println(err) e.println(err)
continue loop
} }
} }
} }