robfig / cron

a cron library for go
MIT License
13.05k stars 1.62k forks source link

Execute the function in the scheduled task immediately when the program starts。 #342

Open wuruipeng404 opened 4 years ago

wuruipeng404 commented 4 years ago

For example, I have a task that is executed every minute. When I start the program, cron will start to execute my task in the next minute. Can I add an option such as "Execute once now" task。

If I manually call the task once in the program, it will look very ugly, and some situations cannot be satisfied

windzhu0514 commented 3 years ago

you can write a custom schedule,but this only support stand parser.

type StartNowSchedule struct {
    firstTime int32
    schedule  cron.Schedule
}

func NewStartNow(spec string) (*StartNowSchedule, error) {
    schedule, err := cron.ParseStandard(spec)
    if err != nil {
        return nil, err
    }

    return &StartNowSchedule{schedule: schedule}, nil
}

func (schedule *StartNowSchedule) Next(t time.Time) time.Time {
    if schedule.firstTime == 0 {
        schedule.firstTime = 1
        return t
    }

    return schedule.schedule.Next(t)
}
ivanjaros commented 3 years ago

this is quite needed indeed. the AddJob(spec string, cmd Job) could be simply refactored to AddJob(spec string, cmd Job, runOnStart ...bool) to keep the backwards compatibility and the scheduler would fire the tasks one after another in the order they were added.