feat: remove and clear task

This commit is contained in:
Noah Hsu
2022-07-31 21:21:54 +08:00
parent be452aafde
commit cb06d3a19a
5 changed files with 98 additions and 1 deletions

View File

@ -4,4 +4,5 @@ import "errors"
var (
ErrTaskNotFound = errors.New("task not found")
ErrTaskRunning = errors.New("task is running")
)

View File

@ -72,8 +72,16 @@ func (tm *Manager[K]) Cancel(tid K) error {
return nil
}
func (tm *Manager[K]) Remove(tid K) {
func (tm *Manager[K]) Remove(tid K) error {
t, ok := tm.Get(tid)
if !ok {
return errors.WithStack(ErrTaskNotFound)
}
if !t.Done() {
return errors.WithStack(ErrTaskRunning)
}
tm.tasks.Delete(tid)
return nil
}
// RemoveAll removes all tasks from the manager, this maybe shouldn't be used
@ -110,6 +118,10 @@ func (tm *Manager[K]) ListDone() []*Task[K] {
return tm.GetByStates(SUCCEEDED, CANCELED, ERRORED)
}
func (tm *Manager[K]) ClearDone() {
tm.RemoveByStates(SUCCEEDED, CANCELED, ERRORED)
}
func NewTaskManager[K comparable](maxWorker int, updateID ...func(*K)) *Manager[K] {
tm := &Manager[K]{
tasks: generic_sync.MapOf[K, *Task[K]]{},

View File

@ -3,6 +3,7 @@ package task
import (
"context"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
@ -91,6 +92,10 @@ func (t *Task[K]) retry() {
t.run()
}
func (t *Task[K]) Done() bool {
return t.state == SUCCEEDED || t.state == CANCELED || t.state == ERRORED
}
func (t *Task[K]) Cancel() {
if t.state == SUCCEEDED || t.state == CANCELED {
return