Quartz 调度器执行一个 Runnable

Quartz scheduler execute an Runnable

Quartz Scheduler 可以执行 Runnable 吗?

例如,我有以下代码 运行 由 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));
[...]

我想用 Quartz 做类似上面代码的事情,我知道有 QuartzJobBean class,但是这个 仅适用于静态代码,我需要动态传递 cronExpression 和其他参数。

我发现这段代码:QuartzScheduledExecutorService.java 可以帮助我解决这个问题。也许它可以在将来帮助其他人。

您可以定义一个作业,它通过 JobDataMap 执行 Runnable,并在执行时执行 运行。

这份工作看起来像这样:

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();
    }
}

你安排工作的地方看起来像这样:

        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);