任務 API
最後更新
本頁列出
core 中註冊、移除與列出任務的方法,以及任務狀態常數。Add
- func (c *cron) Add(spec string, action interface{}, arg ...interface{}) (int64, error)
| 參數 | 型別 | 說明 |
|---|---|---|
spec | string | 五欄位 Cron、描述符或 @every <duration> |
action | func() 或 func() error | 任務本體 |
arg | string、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 support | func() 搭配 []Wait 或 []int64 |
空字串
spec 不會回傳錯誤:解析器會先讀取 spec[0],因此 Add("", ...) 會以 index out of range panic。Remove 與 RemoveAll
Remove
- func (c *cron) Remove(id int64)
停用並自最小堆移除指定 ID 的任務;ID 不存在時無動作。
RemoveAll
- func (c *cron) RemoveAll()
執行中時清空最小堆;未啟動時停用全部任務。
List
- func (c *cron) List() []*task
回傳目前最小堆中啟用中任務的指標,匯出欄位為
ID int64。List 會持有排程器的 mutex,但 Start 後事件迴圈 goroutine 修改最小堆時不取得該 mutex,因此在排程器執行中呼叫 List 會被 go test -race 回報為 data race。- for _, t := range c.List() {
- log.Println(t.ID)
- }
任務狀態常數
- const (
- TaskPending int = iota
- TaskRunning
- TaskCompleted
- TaskFailed
- )
狀態轉換規則見 任務模型。