v1.2.1

Task API

Last updated


This page lists the core methods for registering, removing, and listing tasks, plus the task state constants.

Add


  1. func (c *cron) Add(spec string, action interface{}, arg ...interface{}) (int64, error)

ParameterTypeDescription
specstring5-field cron, descriptor, or @every <duration>
actionfunc() or func() errorTask body
argstring, time.Duration, func(), []Wait, []int64Description, execution limit, timeout callback, prerequisites

ReturnCondition
id > 0, nilRegistered
0, failed to parse: ...Invalid field count, range, step, or duration in spec, or @every below 30 seconds
0, action need to be func() or func()Unsupported action type
0, need return value to get dependence supportfunc() combined with []Wait or []int64

An empty spec is not rejected with an error: the parser reads spec[0] first, so Add("", ...) panics with index out of range.

Remove and RemoveAll


Remove


  1. func (c *cron) Remove(id int64)

Disables the task with the given ID and removes it from the heap; no-op when the ID does not exist.

RemoveAll


  1. func (c *cron) RemoveAll()

Clears the heap while running; disables every task before Start.

List


  1. func (c *cron) List() []*task

Returns pointers to enabled tasks in the heap; the exported field is ID int64. List holds the scheduler mutex, but after Start the event loop goroutine modifies the heap without that mutex, so calling List while the scheduler is running is reported as a data race by go test -race.
  1. for _, t := range c.List() {
  2. log.Println(t.ID)
  3. }

Task State Constants


  1. const (
  2. TaskPending int = iota
  3. TaskRunning
  4. TaskCompleted
  5. TaskFailed
  6. )

See Task Model for state transition rules.
中文