Just annotate your Quartz-Jobs with @Scheduled
and they will get
picked up and passed to the scheduler automatically (during the
bootstrapping process).
Scheduled task based on org.quartz.Job
@Scheduled(cronExpression = "0 0/10 * * * ?")
public class CdiAwareQuartzJob implements org.quartz.Job
{
@Inject
private MyService service;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
{
}
}
As an alternative it’s possible to annotate an implementation of java.lang.Runnable
(since DeltaSpike v1.5.3):
Scheduled task based on java.lang.Runnable
@Scheduled(cronExpression = "0 0/10 * * * ?")
public class CdiAwareRunnableJob implements java.lang.Runnable
{
@Inject
private MyService service;
@Override
public void run()
{
}
}
Behind the scenes DeltaSpike registers an adapter for Quartz which just delegates to the run
-method once the adapter gets called by Quartz.
Technically you end up with almost the same, just with a reduced API for implementing (all) your scheduled jobs.
Therefore the main difference is that your code is independent of Quartz-classes.
However, you need to select org.quartz.Job
or java.lang.Runnable
for all your scheduled-tasks, bot not both!
In such scheduled-tasks CDI based dependency-injection is enabled.
Furthermore, the request- and session-scope get started (and stopped)
per job-execution. Therefore, the container-control module (of
DeltaSpike) is required. That can be controlled via
@Scheduled#startScopes
(possible values: all scopes supported by the
container-control module as well as {}
for 'no scopes').
With 'false' for @Scheduled#onStartup
, it is even possible to
schedule/install jobs dynamically.
The following example shows how to use it, if you are using org.quartz.Job
(and not java.lang.Runnable
).
Example
@ApplicationScoped
public class ProjectStageAwareSchedulerController
{
@Inject
private Scheduler<Job> jobScheduler;
@Inject
private ProjectStage projectStage;
public void registerJobs()
{
if (ProjectStage.Production.equals(this.projectStage))
{
this.jobScheduler.registerNewJob(ManualCdiAwareQuartzJob.class);
}
}
@Scheduled(cronExpression = "0 0/10 * * * ?", onStartup = false)
public class ManualCdiAwareQuartzJob implements org.quartz.Job
{
@Inject
private MyService service;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
{
}
}
}