chore: add state for task
This commit is contained in:
@ -20,34 +20,40 @@ type Func[K comparable] func(task *Task[K]) error
|
||||
type Callback[K comparable] func(task *Task[K])
|
||||
|
||||
type Task[K comparable] struct {
|
||||
ID K
|
||||
Name string
|
||||
Status string
|
||||
Error error
|
||||
ID K
|
||||
Name string
|
||||
state string // pending, running, finished, canceling, canceled, errored
|
||||
status string
|
||||
progress int
|
||||
|
||||
Error error
|
||||
|
||||
Func Func[K]
|
||||
callback Callback[K]
|
||||
|
||||
Ctx context.Context
|
||||
progress int
|
||||
cancel context.CancelFunc
|
||||
Ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (t *Task[K]) SetStatus(status string) {
|
||||
t.Status = status
|
||||
t.status = status
|
||||
}
|
||||
|
||||
func (t *Task[K]) SetProgress(percentage int) {
|
||||
t.progress = percentage
|
||||
}
|
||||
|
||||
func (t *Task[K]) GetState() string {
|
||||
return t.state
|
||||
}
|
||||
|
||||
func (t *Task[K]) run() {
|
||||
t.Status = RUNNING
|
||||
t.state = RUNNING
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Errorf("error [%+v] while run task [%s]", err, t.Name)
|
||||
t.Error = errors.Errorf("panic: %+v", err)
|
||||
t.Status = ERRORED
|
||||
t.state = ERRORED
|
||||
}
|
||||
}()
|
||||
t.Error = t.Func(t)
|
||||
@ -55,11 +61,11 @@ func (t *Task[K]) run() {
|
||||
log.Errorf("error [%+v] while run task [%s]", t.Error, t.Name)
|
||||
}
|
||||
if errors.Is(t.Ctx.Err(), context.Canceled) {
|
||||
t.Status = CANCELED
|
||||
t.state = CANCELED
|
||||
} else if t.Error != nil {
|
||||
t.Status = ERRORED
|
||||
t.state = ERRORED
|
||||
} else {
|
||||
t.Status = FINISHED
|
||||
t.state = FINISHED
|
||||
if t.callback != nil {
|
||||
t.callback(t)
|
||||
}
|
||||
@ -71,20 +77,20 @@ func (t *Task[K]) retry() {
|
||||
}
|
||||
|
||||
func (t *Task[K]) Cancel() {
|
||||
if t.Status == FINISHED || t.Status == CANCELED {
|
||||
if t.state == FINISHED || t.state == CANCELED {
|
||||
return
|
||||
}
|
||||
if t.cancel != nil {
|
||||
t.cancel()
|
||||
}
|
||||
// maybe can't cancel
|
||||
t.Status = CANCELING
|
||||
t.state = CANCELING
|
||||
}
|
||||
|
||||
func WithCancelCtx[K comparable](task *Task[K]) *Task[K] {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
task.Ctx = ctx
|
||||
task.cancel = cancel
|
||||
task.Status = PENDING
|
||||
task.state = PENDING
|
||||
return task
|
||||
}
|
||||
|
Reference in New Issue
Block a user