cron icon indicating copy to clipboard operation
cron copied to clipboard

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

Open wuruipeng404 opened this issue 5 years ago • 3 comments

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

wuruipeng404 avatar Sep 24 '20 05:09 wuruipeng404

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)
}

windzhu0514 avatar Nov 13 '20 06:11 windzhu0514

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.

ivanjaros avatar Nov 24 '20 15:11 ivanjaros