spring quartz tutorial sample code first commit

This commit is contained in:
sriv-priyank 2015-09-30 23:30:45 +05:30
parent a5375cb90c
commit e57088cfa4
16 changed files with 451 additions and 0 deletions

3
spring-quartz/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
*.iml
.idea
target/

4
spring-quartz/README.md Normal file
View File

@ -0,0 +1,4 @@
=========
## Scheduling in Spring with Quartz Example Project

38
spring-quartz/pom.xml Normal file
View File

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-quartz</artifactId>
<version>0.0.1-SNAPSHOT</version>
<modules>
<module>spring-quartz-basics</module>
</modules>
<packaging>pom</packaging>
<name>spring-quartz</name>
<description>Demo project for Scheduling in Spring with Quartz</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,2 @@
target/
*.iml

View File

@ -0,0 +1,22 @@
=========================================================================
## Scheduling in Spring with Quartz Example Project
This is the first example where we configure a basic scheduler.
##### Spring boot application, Main class
###
```
SpringQuartzBasicsApp
```
######
##### Configuration in *application.properties*
####
- Default: configures scheduler using Spring convenience classes:
```
using.spring.schedulerFactory=true
```
- To configure scheduler using Quartz API:
```
using.spring.schedulerFactory=false
```

View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-quartz-basics</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>spring-quartz-basics</name>
<description>Demo project for Scheduling in Spring with Quartz</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- spring's support for quartz -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<!-- tests -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,16 @@
package org.baeldung.springquartz;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan
@EnableScheduling
public class SpringQuartzBasicsApp {
public static void main(String[] args) {
SpringApplication.run(SpringQuartzBasicsApp.class, args);
}
}

View File

@ -0,0 +1,35 @@
package org.baeldung.springquartz.config;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
/**
* Adds auto-wiring support to quartz jobs.
* @see "https://gist.github.com/jelies/5085593"
*/
public final class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory
implements ApplicationContextAware {
private transient AutowireCapableBeanFactory beanFactory;
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
beanFactory = applicationContext.getAutowireCapableBeanFactory();
}
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle)
throws Exception {
final Object job = super.createJobInstance(bundle);
beanFactory.autowireBean(job);
return job;
}
}

View File

@ -0,0 +1,86 @@
package org.baeldung.springquartz.scheduler;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import javax.annotation.PostConstruct;
import java.io.IOException;
@Configuration
@ConditionalOnExpression("'${using.spring.schedulerFactory}'=='false'")
public class QrtzScheduler {
Logger _logger = LoggerFactory.getLogger(getClass());
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
public void init() {
_logger.info("Hello world from Quartz...");
}
@Bean(name = "SpringJobFactory")
public SpringBeanJobFactory springBeanJobFactory() {
AutoWiringSpringBeanJobFactory jobFactory = new AutoWiringSpringBeanJobFactory();
_logger.debug("Configuring Job factory");
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
@Bean(name = "Qrtz_Scheduler")
public Scheduler scheduler(@Qualifier("Qrtz_Trigger") Trigger trigger,
@Qualifier("Qrtz_Job_Detail") JobDetail job) throws SchedulerException, IOException {
StdSchedulerFactory factory = new StdSchedulerFactory();
factory.initialize(new ClassPathResource("quartz.properties").getInputStream());
_logger.debug("Getting a handle to the Scheduler");
Scheduler scheduler = factory.getScheduler();
scheduler.setJobFactory(springBeanJobFactory());
scheduler.scheduleJob(job, trigger);
_logger.debug("Starting Scheduler threads");
scheduler.start();
return scheduler;
}
@Bean(name = "Qrtz_Job_Detail")
public JobDetail jobDetail() {
return newJob().ofType(SampleJob.class).storeDurably().withIdentity("Qrtz_Job_Detail")
.withDescription("Invoke Sample Job service...").build();
}
@Bean(name = "Qrtz_Trigger")
public Trigger trigger(@Qualifier("Qrtz_Job_Detail") JobDetail job) {
int frequencyInSec = 10;
_logger.info("Configuring trigger to fire every {} seconds", frequencyInSec);
return newTrigger().forJob(job).withIdentity("Qrtz_Trigger")
.withDescription("Sample trigger")
.withSchedule(
simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever())
.build();
}
}

View File

@ -0,0 +1,30 @@
package org.baeldung.springquartz.scheduler;
import org.baeldung.springquartz.service.SampleJobService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
public class SampleJob implements Job {
Logger _logger = LoggerFactory.getLogger(getClass());
@Autowired
private SampleJobService jobService;
public void execute(JobExecutionContext context) throws JobExecutionException {
_logger.info("Job **{}** fired @ {}", context.getJobDetail().getKey().getName(),
context.getFireTime());
jobService.executeSampleJob();
_logger.info("Next job scheduled @ {}", context.getNextFireTime());
}
}

View File

@ -0,0 +1,85 @@
package org.baeldung.springquartz.scheduler;
import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import javax.annotation.PostConstruct;
@Configuration
@ConditionalOnExpression("'${using.spring.schedulerFactory}'=='true'")
public class SpringQrtzScheduler {
Logger _logger = LoggerFactory.getLogger(getClass());
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
public void init() {
_logger.info("Hello world from Spring...");
}
@Bean(name = "SpringJobFactory")
public SpringBeanJobFactory springBeanJobFactory() {
AutoWiringSpringBeanJobFactory jobFactory = new AutoWiringSpringBeanJobFactory();
_logger.debug("Configuring Job factory");
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
@Bean(name = "Spring_Scheduler")
public SchedulerFactoryBean scheduler(@Qualifier("Spring_Trigger") Trigger trigger,
@Qualifier("Spring_Job_Detail") JobDetail job) {
SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
schedulerFactory.setConfigLocation(new ClassPathResource("quartz.properties"));
_logger.debug("Setting the Scheduler up");
schedulerFactory.setJobFactory(springBeanJobFactory());
schedulerFactory.setJobDetails(job);
schedulerFactory.setTriggers(trigger);
return schedulerFactory;
}
@Bean(name = "Spring_Job_Detail")
public JobDetailFactoryBean jobDetail() {
JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
jobDetailFactory.setJobClass(SampleJob.class);
jobDetailFactory.setDescription("Invoke Sample Job service...");
jobDetailFactory.setDurability(true);
return jobDetailFactory;
}
@Bean(name = "Spring_Trigger")
public SimpleTriggerFactoryBean trigger(@Qualifier("Spring_Job_Detail") JobDetail job) {
SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
trigger.setJobDetail(job);
int frequencyInSec = 10;
_logger.info("Configuring trigger to fire every {} seconds", frequencyInSec);
trigger.setRepeatInterval(frequencyInSec*1000);
trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
return trigger;
}
}

View File

@ -0,0 +1,24 @@
package org.baeldung.springquartz.service;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class SampleJobService {
private Logger _log = LoggerFactory.getLogger(getClass());
public void executeSampleJob() {
_log.info("The sample job has begun...");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
_log.error("Error while executing sample job", e);
} finally {
_log.info("Sample job has finished...");
}
}
}

View File

@ -0,0 +1 @@
using.spring.schedulerFactory=true

View File

@ -0,0 +1,16 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,10 @@
# thread-pool
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=2
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true
# job-store
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
# others
org.quartz.jobStore.misfireThreshold = 60000

View File

@ -0,0 +1,13 @@
package org.baeldung.springquartz;
//@RunWith(SpringJUnit4ClassRunner.class)
//@SpringApplicationConfiguration(classes = SpringQuartzBasicsApp.class)
public class SpringQuartzApplicationTests {
// @Test
public final void whenContextIsBootstrapped_thenNoExceptions() {
System.out.println("Context bootstrapped...");
}
}