为什么gocron会多次执行?

时间:2018-03-10 18:45:08

标签: go cron scheduled-tasks

我正在尝试构建一个按cron计划执行的服务。我正在尝试使用gocron(https://github.com/jasonlvhit/gocron)。我的代码如下所示:

func taskWithParams(a int, b string) {
    fmt.Println(a, b)
}

func GetSchedules() {
    s := gocron.NewScheduler()

    //Retrieve the schedules from Dyanmo
    var scheduleArray = dynamodb.GetConfiguration()

    //iterate over all of the schedules
    for _, i := range scheduleArray {

        //Determine the days we need to schedule on
        dayWeekStart, err := strconv.Atoi(i.Cron["day_week_start"])
        dayWeekEnd, err := strconv.Atoi(i.Cron["day_week_end"])
        if err != nil {
            fmt.Println("error getting days:", err)
        }

        //Determine the time to execute on
        var timeToRun string
        buffer := bytes.NewBufferString("")
        buffer.WriteString(i.Cron["hour"])
        buffer.WriteString(":")
        buffer.WriteString(i.Cron["min"])
        timeToRun = buffer.String()

        for x := dayWeekStart; x <= dayWeekEnd; x++ {
            switch {
            case x == 0:
                s.Every(1).Sunday().At(timeToRun).Do(taskWithParams, 0, timeToRun)
            case x == 1:
                s.Every(1).Monday().At(timeToRun).Do(taskWithParams, 1, timeToRun)
            case x == 2:
                s.Every(1).Tuesday().At(timeToRun).Do(taskWithParams, 2, timeToRun)
            case x == 3:
                s.Every(1).Wednesday().At(timeToRun).Do(taskWithParams, 3, timeToRun)
            case x == 4:
                s.Every(1).Thursday().At(timeToRun).Do(taskWithParams, 4, timeToRun)
            case x == 5:
                s.Every(1).Friday().At(timeToRun).Do(taskWithParams, 5, timeToRun)
            case x == 6:
                s.Every(1).Saturday().At(timeToRun).Do(taskWithParams, 6, timeToRun)
            default:
                fmt.Println("Improper cron day of week")
            }
        }
    }
    <-s.Start()
}

现在,说我有一个cron时间表在周一至周五中午执行。星期一中午到来时,输出如下:

  • 1 12:00
  • 2 12:00
  • 3 12:00
  • 4 12:00
  • 5 12:00

为什么周一周五周五执行?这些例子似乎很简单。我觉得我在做一些愚蠢的事情但却无法看到它。

0 个答案:

没有答案