Search code examples
javaspring-bootquartz

Quartz scheduler execute an Runnable


Can a Quartz Scheduler execute a Runnable?

For example, I have the following code being running by a spring TaskScheduler:

[...]
@Autowired
@Qualifier(IntegrationConfiguration.TASK_SCHEDULER_INTEGRATION_NAME)
private TaskScheduler taskScheduler;

[...]
ScheduledFuture<?> scheduledFuture = taskScheduler.schedule(new Runnable() {

    @Override
    public void run() {
        try {
            execucaoJobService.executa(jobName, execucaoJobDto, jobScheduleId);
        } catch (JobExecutionException e) {
            LOG.error("Job Execution fails", e);
        }
    }
}, new CronTrigger(cronExpression));
[...]

I wanna do something like the above code with Quartz, I know there is QuartzJobBean class, but this one only works with static code, and I need to pass the cronExpression and other params dynamic.


Solution

  • You could define a job that takes a Runnable via the JobDataMap, and run that on execution.

    The job would look like this:

    public final class RunnableJob implements Job {
    
        public static final String RUNNABLE_KEY = "RUNNABLE_KEY";
    
        public RunnableJob() {
            // Explicit constructor is required by Quartz.
        }
    
        @Override
        public void execute(JobExecutionContext jobExecutionContext) {
            final var runnable = (Runnable) jobExecutionContext.getJobDetail().getJobDataMap().get(RUNNABLE_KEY);
            runnable.run();
        }
    }
    

    Where you schedule your job it would look something like this:

            final var cronTrigger = TriggerBuilder.newTrigger()
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .build();
    
            final var jobDetail = JobBuilder.newJob(RunnableJob.class)
                .setJobData(new JobDataMap(Map.of(RunnableJob.RUNNABLE_KEY,
                    (Runnable) () -> {
                        // Do whatever you want to do
                    })))
                .build();
    
            scheduler.scheduleJob(jobDetail, cronTrigger);