DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Clustered Quartz Scheduler With Spring Boot and MongoDB
  • How to Marry MDC With Spring Integration
  • Integrate Spring With Open AI
  • DZone Community Awards 2022

Trending

  • Why AI-Generated Code Breaks Your Testing Assumptions
  • Run Gemma 4 on Your Laptop: A Hands-On Guide to Google's Latest Open Multimodal LLM
  • Agentic Testing: Moving Quality From Checkpoint to Control Layer
  • S3 Vectors: How to Build a RAG Without a Vector Database
  1. DZone
  2. Culture and Methodologies
  3. Career Development
  4. Spring and Quartz Integration That Works Together Smoothly

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.

By 
Rakshit Jain user avatar
Rakshit Jain
·
Apr. 11, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
31.8K Views

Join the DZone community and get the full member experience.

Join For Free

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);
    }
}
Spring Framework Quartz (scheduler) job scheduling career Integration

Opinions expressed by DZone contributors are their own.

Related

  • Clustered Quartz Scheduler With Spring Boot and MongoDB
  • How to Marry MDC With Spring Integration
  • Integrate Spring With Open AI
  • DZone Community Awards 2022

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook