Search code examples
javaasynchronousjbosscronquartz-scheduler

JAVA: Run the cron job task even schedule has come


I already checked here but seems no solution given.

Here is my problem.

I have a cron job in my seam project which is written with jboss async. It runs at 3am everyday.

However last night, the application needed to reboot before that time. Past 3am when the application started.

The task set to run every 3am but did not run. In the code, the final expiration is set to 12/31/9999. Technically speaking, this will assume that it is already done.

Is there any chance to still run that job even past of scheduled given since it never run at that time? Like executing it right after the application is ready for production. If there are solutions, how would I make it?

Putting some flag to check if the job is done would be the least option.

Here is my sample code.

public void someMethodToSetJob() {
    final String cronTabSchedule = "0 0 3 ? * MON-FRI *";
    final Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MINUTE, 1);
    cal.set(Calendar.SECOND, 0);

    final Calendar expiry = Calendar.getInstance();
    expiry.set(Calendar.MONTH, 11);
    expiry.set(Calendar.DATE, 31);
    expiry.set(Calendar.YEAR, 9999);
    expiry.set(Calendar.SECOND, 0);

    processBackgroundProcessCheck(cal.getTime(), cronTabSchedule, expiry.getTime());
}



@Asynchronous
@Transactional(TransactionPropagationType.REQUIRED)
public QuartzTriggerHandle processBackgroundProcessCheck(
        @Expiration final Date when,
        @IntervalCron final String cron,
        @FinalExpiration final Date endDate) {
    ...
    return null;
}

Any help would be highly appreciated. Thanks!


Solution

  • It is possible by backdating the begin date which is @Expiration. Since I have in CRON schedule at 3AM, then let's say the application is deployed at 4AM. By setting the Date for @Expiration into something that it would catch the 3AM. it will run the process at the very moment. But the next schedule will be exactly 3AM.

    public void someMethodToSetJob() {
        final String cronTabSchedule = "0 0 3 ? * MON-FRI *";
        final Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR_OF_DAY, 3);
        cal.set(Calendar.SECOND, 0);
    
        final Calendar expiry = Calendar.getInstance();
        expiry.set(Calendar.MONTH, 11);
        expiry.set(Calendar.DATE, 31);
        expiry.set(Calendar.YEAR, 9999);
        expiry.set(Calendar.SECOND, 0);
    
        processBackgroundProcessCheck(cal.getTime(), cronTabSchedule, expiry.getTime());
    }