Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring and Quartz Integration That Works Together Smoothly

DZone's Guide to

Spring and Quartz Integration That Works Together Smoothly

In this post, we learn how to integrate a library that allows for scheduling jobs in a Java app into a Spring-based application.

· Integration Zone ·
Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

When it comes to scheduling jobs in a Java application, Quartz is the first tool that comes into consideration. Quartz is a job scheduler backed by the most popular RDBMSs. It is really convenient and integrates with Spring quite easily.

The situation gets trickier when beans of Quartz are not managed by Spring. In this case, we are not able to use Spring DI, AOP, etc., in Quartz jobs. Many people do complain that they are not able to auto-wire dependencies in Quartz jobs or they are not able to perform other aspects of their Quartz jobs.

My Goal: Use Spring features such as AOP and DI in Quartz jobs.

Enough talking, let's jump into the solution.

Quartz Configuration

Configure Quartz and Spring to work together. In this configuration, we are assuming that we will be creating dynamic triggers. However, if you have static triggers in your application you can auto-wire them here.

@Configuration
public class QuartzConfiguration
{
    @Value("${quartz.configLocation}")
    private Resource configLocation;

   //Auto wire static triggers. 
   /** @Autowire
   List<Triggers> triggers;**/

    @Bean
    public JobFactory jobFactory(ApplicationContext applicationContext)
    {
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(@Autowired DataSource dataSource,
                                                     @Autowired JobFactory jobFactory) throws IOException
    {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setOverwriteExistingJobs(true);
        factory.setAutoStartup(true);
        factory.setDataSource(dataSource);
        //This is the place where we will wire Quartz and Spring together
        factory.setJobFactory(jobFactory);
        factory.setQuartzProperties(quartzProperties());
        //factory.setTriggers(triggers);
        return factory;
    }

    @Bean
    public Properties quartzProperties() throws IOException
    {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(configLocation);
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

}

AutowiringSpringBeanJobFactory: This is the place where all the magic happens. Here we have configured a JobFactory that will be auto-wired in a Quartz configuration. By making it Application Context-aware we are bringing Spring and Quartz together.

Job job = ctx.getBean(bundle.getJobDetail().getJobClass());

Here we are getting the Job instance from the application context which will be returned when executing your job's method. This is important because we want to make sure spring managed beans are used so all features of spring can work smoothly.

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
        ApplicationContextAware
{

    private ApplicationContext ctx;
    private SchedulerContext schedulerContext;

    @Override
    public void setApplicationContext(final ApplicationContext context)
    {
        this.ctx = context;
        ;
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception
    {
        Job job = ctx.getBean(bundle.getJobDetail().getJobClass());
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);
        MutablePropertyValues pvs = new MutablePropertyValues();
        pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap());
        pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());
        if (this.schedulerContext != null)
        {
            pvs.addPropertyValues(this.schedulerContext);
        }
        bw.setPropertyValues(pvs, true);
        return job;
    }

    public void setSchedulerContext(SchedulerContext schedulerContext)
    {
        this.schedulerContext = schedulerContext;
        super.setSchedulerContext(schedulerContext);
    }
}

Now it’s time to create your Job.

@Component
@DisallowConcurrentExecution
public class EmailJob implements Job
{
    private static final Logger LOGGER =     LoggerFactory.getLogger(EmailJob.class);

    private final EmailSenderService emailSenderService;


    @Autowired
    public EmailJob(EmailSenderService emailSenderService)
    {
        this.emailSenderService = emailSenderService;
    }


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException
    {

        LOGGER.info("Executing email sender job");
        emailSenderService.sendEmail();
    }

}

Now, let’s create a Scheduler service (SchedulerService) to create Triggers. This service can be triggered by your controller.

@Component
public class SchedulerService
{
    private Scheduler scheduler;

    public ReportSchedulerService(@Autowired Scheduler scheduler)
    {
        this.scheduler = scheduler;
    }

    public void createSchedule(String cronExpression) throws SchedulerException
    {
        JobKey jobKey = new JobKey("EmailJob", "Let's Spam everyone");

        ScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger-" + "EmailJob", "Let's Spam everyone")
                .startNow()
                .withSchedule(scheduleBuilder)
                .build();

        JobDetail jobDetail = newJob(EmailJob.class).withIdentity(jobKey)
                .usingJobData("Job-Id", "1")
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }

    @PreDestroy
    public void preDestroy() throws SchedulerException
    {
        scheduler.shutdown(true);
    }
}

With SnapLogic’s integration platform you can save millions of dollars, increase integrator productivity by 5X, and reduce integration time to value by 90%. Sign up for our risk-free 30-day trial!

Topics:
spring ,quartz ,integration ,java integration

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}