Ayaz Alifov
Ayaz Alifov

Reputation: 8588

Cron expression: Run weekly on Tuesdays and Wednesdays starting NOW

I need some help from people with Cron knowledge. I'm trying to write Cron expression which should run weekly once on Tuesday and once on Wednesday starting immediately if it is Tuesday today. My current solution is:

0 0 * * 2,3

This expression runs Cron at 00:00 on Tuesdays and Wednesdays. But it will not run if it is Tuesday today, because time is already ahead 00:00. If I set time to current hour and minute, let say 16:30, then Cron will start now on Tuesday, but then Wednesday will start at 16:30 as well. I want to start all next Сron events as soon as possible, i.e. on Wednesday's at 00:00

Is it possible to solve this task at all? Many thanks for any effort to help.

Upvotes: 0

Views: 671

Answers (2)

kvantour
kvantour

Reputation: 26481

You could implement a tripple cron of the following type:

* * * * 2 [ ! -e "$HOME/cronflag2" ] && touch "$HOME/cronflag2" && command 
* * * * 3 [ ! -e "$HOME/cronflag3" ] && touch "$HOME/cronflag3" && command
0 0 * * 4 rm "$HOME/cronflag2" "$HOME/cronflag3"

The first command will only execute if a flag-file is not available. If it is not available it will make it and execute the command.

Upvotes: 1

Ken Chan
Ken Chan

Reputation: 90467

Seem that you want to run a job on every TUE and WED 's mid-night, and also want to run immediately when the application start at TUE or WED. Not aware and never heard cron expression can handle that "start immediately" behaviour. But you can use simply use @PostConstruct to achieve it :

public class CronJob {

    @PostConstruct
    public void onStart() {
       LocalDateTime now =LocalDateTime.now();
       if(now.getDayOfWeek() == DayOfWeek.TUESDAY || now.getDayOfWeek() == DayOfWeek.WEDNESDAY  ) {
            if(!now.toLocalTime().equals(LocalTime.MIDNIGHT)) {
                 doJob();
            }
        }

    }

    @Scheduled(cron="0 0 * * 2,3")
    public void onSchedule() {
         doJob();
    }

    public void doJob(){
        //do the job
    }
}

Upvotes: 1

Related Questions