Saturday, January 27, 2024

[SOLVED] execute same cronJob with multiple and dynamic dates

Issue

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() {

  }`


Solution

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.

For Example:

I want to run the task one minute after now. In this case, I use LocalDateTime and convert to Instant.

LocalDateTime oneMinuteAfter = LocalDateTime.now().plusMinutes(1);

executor.schedule(() => {}, oneMinuteAfter.atZone(ZoneId.systemDefault()).toInstant());


Answered By - Arnas
Answer Checked By - Mildred Charles (WPSolving Admin)