Quartz Job Scheduler
Quartz is open source job scheduling service. Quartz can be used to create simple or complex schedules for executing jobs; jobs whose tasks are defined as standard Java components that are programmed to fulfill the requirements of your application.
Spring provides the helper classes to support the Quartz scheduler.
1. Simple Task – perform the required task.
package com.samples.processor;
/**
* class perform the particular task
*
*/
public class SimpleTask {
public void displayText() {
System.out.println("Welcome !!");
}
}
2. Schedular Job
You can define the scheduler job in following way, which will invoke the displayText() method in specified time intervals from SimpleTask.
-- applicationContext.xml
<bean id="simpleTask" class="com.samples.processor.SimpleTask"/>
<bean id="simpleJob"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="simpleTask" />
<property name="targetMethod" value="simpleTask" />
<property name="concurrent" value="false" />
</bean>
<!-- Simple Trigger -->
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="simpleJob" />
<property name="repeatInterval" value="15000" />
<property name="startDelay" value="1000" />
</bean>
<!-- Cron Trigger -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="simpleJob" />
<property name="cronExpression" value="0 0/5 * * * ?" />
</bean>
<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="simpleJob" />
</list>
</property>
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
</bean>
3. Triggers – will be used to specify when should run your job. There are two types of triggers.
- SimpleTrigger – allows us to set start time, end time, repeat interval to run your job.
- CronTrigger – allows us to Unix cron expression to specify the dates and times to run your job.
The Unix cron expression is very flexible, you can see examples in following website.
3. Main Program – start the scheduler
package com.samples.processor;
import org.quartz.impl.StdScheduler;
import org.springframework.context.ApplicationContext;
/**
* Scheduler class starts the job.
*
*/
public class SimpleJobSchedular {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
stdScheduler = (StdScheduler) applicationContext.getBean("schedulerFactoryBean");
stdScheduler.start();
}
}
No comments:
Post a Comment