golang cron裡面經典的取下一次時間

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
func (s *SpecSchedule) Next(t time.Time) time.Time {// General approach:// For Month, Day, Hour, Minute, Second:// Check if the time value matches.  If yes, continue to the next field.// If the field doesn't match the schedule, then increment the field until it matches.// While incrementing the field, a wrap-around brings it back to the beginning// of the field list (since it is necessary to re-verify previous field// values)// 下一次每次取最近1s的時間t = t.Add(1*time.Second - time.Duration(t.Nanosecond())*time.Nanosecond)// This flag indicates whether a field has been incremented.added := false// If no time is found within five years, return zero.yearLimit := t.Year() + 5WRAP:if t.Year() > yearLimit {return time.Time{}}// Find the first applicable month.// If it's this month, then do nothing.    //通過指數法逼近值,並通過從sec到min到hour到day到mon到year的不斷逼近for 1<<uint(t.Month())&s.Month == 0 {// If we have to add a month, reset the other parts to 0.if !added {added = true// Otherwise, set the date at the beginning (since the current time is irrelevant).t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())}t = t.AddDate(0, 1, 0)// Wrapped around.if t.Month() == time.January {goto WRAP}}// Now get a day in that month.for !dayMatches(s, t) {if !added {added = truet = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())}t = t.AddDate(0, 0, 1)if t.Day() == 1 {goto WRAP}}for 1<<uint(t.Hour())&s.Hour == 0 {if !added {added = truet = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), 0, 0, 0, t.Location())}t = t.Add(1 * time.Hour)if t.Hour() == 0 {goto WRAP}}for 1<<uint(t.Minute())&s.Minute == 0 {if !added {added = truet = t.Truncate(time.Minute)}t = t.Add(1 * time.Minute)if t.Minute() == 0 {goto WRAP}}for 1<<uint(t.Second())&s.Second == 0 {if !added {added = truet = t.Truncate(time.Second)}t = t.Add(1 * time.Second)if t.Second() == 0 {goto WRAP}}return t}

 

代碼裡面最經典的還是這種位元運算:

1<<uint(t.Month())&s.Month//轉化為計算公式為: 2^t.Month & s.Month //比如t.Month = 3, s.Month = 4 2^t.Month = 8 > s.Month 並且此時與操作為0//說明此時t.Month與s.Month差距不多,當t.Month=1的時候 2^t.Month = 2 此時與操作結果不為0//當t.Month=2的時候 也是如此//總結就是 2^t.Month > s.Month的時候操作結果為0,需要輪轉到比它小很多的位置,//然後Month的更新再依賴於下面的day的更新

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.