Monday, December 16, 2013

[add-on] simple quartz integration with deltaspike 0.5

the container-control module provided by deltaspike is very powerful. recently i created a simple cdi integration for junit based on this module. integrating a scheduler like quartz is even easer. therefore i prototyped a very simple (= only cron-expressions are supported) deltaspike scheduler add-on. the default-implementation delegates to quartz, however, it's possible to integrate it with any scheduler (if cron-expressions are supported).

the major use-case is simple. just annotate your job-implementations (in case of quartz: org.quartz.Job) with @Scheduled(cronExpression = "[your expression]") and it will be scheduled/installed automatically at the end of the bootstrapping process.

it's possible to use cdi based injection:


@Scheduled(cronExpression = "0 0/10 * * * ?")
public class CdiAwareQuartzJob implements org.quartz.Job
{
@Inject
private MyService service;
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException
{
//...
}
}


furthermore, the request- and session-scope get started (and stopped) per job-execution. however, it can be controlled via @Scheduled#startScopes and it's possible to provide a description as well as a type-safe job-group.

beyond that it's also possible to inject the scheduler and control (scheduleJob, interruptJob, startJobManually,...) it manually - e.g.:
@ApplicationScoped
public class SchedulerController
{
@Inject
private Scheduler<Job> jobScheduler;
public void onPause(@Observes PauseJobEvent /*custom event*/ jobEvent)
{
//using it with events is optional
this.jobScheduler.pauseJob(jobEvent.getJobClass());
}
public void onResume(@Observes ResumeJobEvent /*custom event*/ jobEvent)
{
//using it with events is optional
this.jobScheduler.resumeJob(jobEvent.getJobClass());
}
}


With 'false' for @Scheduled#onStartup it's even possible to schedule/install jobs dynamically - e.g.:
@ApplicationScoped
public class ProjectStageAwareSchedulerController
{
@Inject
private Scheduler<Job> jobScheduler;
@Inject
private ProjectStage projectStage;
public void registerJobs()
{
if (ProjectStage.Production.equals(this.projectStage))
{
//see 'false' for @Scheduled#onStartup
this.jobScheduler.scheduleJob(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
{
//...
}
}
}


Update:
This add-on is part of all versions of DeltaSpike after v0.5