v1.2.1

任務 API

最後更新


本頁列出 core 中註冊、移除與列出任務的方法,以及任務狀態常數。

Add


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

參數型別說明
specstring五欄位 Cron、描述符或 @every <duration>
actionfunc() 或 func() error任務本體
argstring、time.Duration、func()、[]Wait、[]int64描述、執行時限、逾時回呼、前置任務

回傳條件
id > 0, nil註冊成功
0, failed to parse: ...spec 欄位數、範圍、步進或 duration 無效,或 @every 小於 30 秒
0, action need to be func() or func()action 型別不符
0, need return value to get dependence supportfunc() 搭配 []Wait 或 []int64

空字串 spec 不會回傳錯誤:解析器會先讀取 spec[0],因此 Add("", ...) 會以 index out of range panic。

Remove 與 RemoveAll


Remove


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

停用並自最小堆移除指定 ID 的任務;ID 不存在時無動作。

RemoveAll


  1. func (c *cron) RemoveAll()

執行中時清空最小堆;未啟動時停用全部任務。

List


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

回傳目前最小堆中啟用中任務的指標,匯出欄位為 ID int64。List 會持有排程器的 mutex,但 Start 後事件迴圈 goroutine 修改最小堆時不取得該 mutex,因此在排程器執行中呼叫 List 會被 go test -race 回報為 data race。
  1. for _, t := range c.List() {
  2. log.Println(t.ID)
  3. }

任務狀態常數


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

狀態轉換規則見 任務模型。
EN