設定
本頁說明排程器設定,以及傳入個別任務的執行期選項。
排程器設定
core.Config 目前只有一個欄位:
type Config struct {
Location *time.Location
}
Location 控制排程器計算 Cron 表達式或描述符下次觸發時間時使用的時區。core.New 收到 nil 時使用 time.Local。
loc, err := time.LoadLocation("Asia/Taipei")
if err != nil {
return err
}
scheduler, err := core.New(core.Config{
Location: loc,
})
Location 為 nil 時,效果等同於:
scheduler, err := core.New(core.Config{Location: time.Local})
任務選項
任務層級選項透過 Add 的可變參數傳入:
func (c *cron) Add(spec string, action interface{}, arg ...interface{}) (int64, error)
| 參數 | 效果 |
|---|---|
string |
設定任務描述,供排程器 logger 使用。 |
time.Duration |
設定 action 的最長執行時間。 |
func() |
設定 onDelay 回呼,執行逾時時呼叫。 |
[]core.Wait |
宣告前置任務與依賴失敗策略。 |
[]int64 |
已棄用的依賴格式;每個 ID 會轉為 Stop 策略的 Wait。 |
參數可任意順序組合。使用 []core.Wait 或已棄用的 []int64 時,action 必須是 func() error。
scheduler.Add("@every 1m", func() error {
return runReport()
}, "daily report", 30*time.Second, func() {
log.Println("report timeout")
})
逾時行為
傳入的 duration 是執行逾時,不是任務開始前的延遲。action 未在逾時前完成時:
- 任務會標記為失敗;
- 有提供
onDelay時呼叫該回呼; - 將逾時警告寫入設定好的 logger。
action 會在自己的 goroutine 中執行。排程器在期限到達後停止等待,但由於 action API 沒有接收 context,無法強制取消 action goroutine。
scheduler.Add("@every 5m", func() error {
return slowOperation()
}, 10*time.Second, func() {
log.Println("slowOperation exceeded 10 seconds")
})
action 回傳錯誤或 panic 被恢復時,也會產生失敗狀態。func() action 會被包裝成無錯誤 action,正常返回時視為成功。
依賴設定
使用 core.Wait 設定前置任務:
type Wait struct {
ID int64
Delay time.Duration
State WaitState
}
ID指定前置任務。Delay是等待依賴完成的最長時間;零值使用 worker 預設的一分鐘。State為core.Stop或core.Skip。
core.Stop 會在該前置任務失敗時讓相依任務失敗。core.Skip 會忽略失敗的前置任務,繼續評估其他依賴。
prepareID, _ := scheduler.Add("@every 1m", func() error {
return prepare()
})
scheduler.Add("@every 1m", func() error {
return consume()
}, []core.Wait{
{ID: prepareID, Delay: 20 * time.Second, State: core.Stop},
})
排程設定
排程器接受正好五個 Cron 欄位:
| 欄位 | 有效範圍 |
|---|---|
| 分鐘 | 0-59 |
| 小時 | 0-23 |
| 日 | 1-31 |
| 月 | 1-12 |
| 星期 | 0-6(0 為星期日) |
每個欄位支援 *、單一值、範圍、逗號分隔列表與 */n 步進。也支援內建描述符 @yearly、@annually、@monthly、@weekly、@daily、@midnight 與 @hourly。@every <duration> 的最小間隔為 30 秒。
Logger 與 worker 執行期
core.New 會以 goCron 識別字嘗試建立 syslog writer。失敗時改用寫入 stderr 的文字 logger。依賴子系統起始使用兩個 worker;主機回報超過兩個 CPU 時,會使用 runtime.NumCPU() 個 worker。
目前 core 套件不需要環境變數或外部設定檔。執行期設定透過 core.Config 與 Add 參數提供。