Home > Net >  execute same cronJob with multiple and dynamic dates
execute same cronJob with multiple and dynamic dates

Time:12-23

please i need help with this :

i'm developing an application where the user select multiple dates from a calendar in the frontend and those dates are sent to the spring-boot backend and stored into a database. On those exact dates i need to execute a cronjob (let's say send an email).

-First of all : i have convert each date to a cron schedule expressions for example the user choose 3 dates and the result is a list of 3 cron expressions as below :

[ "0 0 8-10 * * " , " 30 16 * * " , " * 9 * * " ]

how can i dynamically execute the same job 3 times with the 3 differents cron expressions ??? :

`@Scheduled(cron = "cron[0]" & "cron[1]" & "cron[2]") // <--- this is what i need 
  private void sendEmail() {

  }`

CodePudding user response:

You can use TaskScheduler for dynamic scheduling based on data. Like this:

import org.springframework.scheduling.TaskScheduler;

private final TaskScheduler executor;

String[] cronList = { "0 0 8-10 * * " , " 30 16 * * " , " * 9 * * " };

for (String cron: cronList) {
    executor.schedule(() -> {
        // do your job here
    }, new CronTrigger(cron));
}

In your case, you don't need to convert Date to a cron expression. You can specify Date or Instant as a parameter. Read this documentation.

executor.schedule(() -> {}, someDate);

CodePudding user response:

Annotations work with constant expressions. So You can not put dynamic expressions inside an annotation. The compiler should show you an error, which explains exactly this.

You could create one method, which is executed every minute (with @Scheduled annotation). This method calls database and sends Email to users inside your database, which fit to current timeslot.

More details about @Scheduled in my German blog:
https://agile-coding.blogspot.com/2021/03/spring-cronjobs.html

CodePudding user response:

You cannot schedule the cron job dynamically using the @Scheduled annotation. For this you need something like the TaskScheduler suggested in another answer.

In case you have a static configuration such that you would like to schedule the same job with different cron expressions you can use the @Schedule annotation if you refactor the code slightly. For example, you can extract the business logic to a separate method and then have three cron-annotated method delegate to that method, e.g.

private void sendEmail() {
    // lengthy method that does the actual work
}

@Scheduled(cron = "0 0 8-10 * *")
private void firstCron() {
    sendEmail();    
}

@Scheduled(cron = "30 16 * *")
private void secondCron() {
    sendEmail();        
}

@Scheduled(cron = "* 9 * *")
private void thirdCron() {
    sendEmail();        
}
  • Related