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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Clustered Quartz Scheduler With Spring Boot and MongoDB
  • Adding a RESTful API for the Quartz Scheduler
  • Run a Spring Batch Job With Quartz
  • DZone Community Awards 2022

Trending

  • CI/CD Software Design Patterns and Anti-Patterns
  • Distributed Cloud Architecture for Resilient Systems
  • DZone's Article Submission Guidelines
  • How to Submit a Post to DZone
  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.

Rakshit Jain user avatar by
Rakshit Jain
·
Apr. 11, 18 · Tutorial
Like (4)
Save
Tweet
Share
30.5K 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
  • Adding a RESTful API for the Quartz Scheduler
  • Run a Spring Batch Job With Quartz
  • DZone Community Awards 2022

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: