Example to run multiple jobs in Quartz

In this example, we show you how to declare multiple Quartz jobs via Quartz APIs, Quartz XML and Spring. In Quartz scheduler framework, each job will be attached to an unique trigger, and run it by scheduler.

P.S In Quartz, one trigger for multiple jobs is not possible. (Correct me if this is wrong.)

1. Quartz APIs

Create 3 Quartz’s jobs, JobA, JobB and JobC.


package com.mkyong.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class JobA implements Job {

	@Override
	public void execute(JobExecutionContext context)
		throws JobExecutionException {
		System.out.println("Job A is runing");
	}

}

package com.mkyong.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class JobB implements Job {

	@Override
	public void execute(JobExecutionContext context)
		throws JobExecutionException {
		System.out.println("Job B is runing");
	}

}

package com.mkyong.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class JobC implements Job {

	@Override
	public void execute(JobExecutionContext context)
		throws JobExecutionException {
		System.out.println("Job C is runing");
	}

}

Use Quartz APIs to declare above 3 Jobs, assigned to 3 particular triggers and schedule it.


package com.mkyong.quartz;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class CronTriggerExample {
	public static void main( String[] args ) throws Exception
    {
    	   	
	JobKey jobKeyA = new JobKey("jobA", "group1");
    	JobDetail jobA = JobBuilder.newJob(JobA.class)
		.withIdentity(jobKeyA).build();

    	JobKey jobKeyB = new JobKey("jobB", "group1");
    	JobDetail jobB = JobBuilder.newJob(JobB.class)
		.withIdentity(jobKeyB).build();

    	JobKey jobKeyC = new JobKey("jobC", "group1");
    	JobDetail jobC = JobBuilder.newJob(JobC.class)
		.withIdentity(jobKeyC).build();

    	
    	Trigger trigger1 = TriggerBuilder
		.newTrigger()
		.withIdentity("dummyTriggerName1", "group1")
		.withSchedule(
			CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
		.build();
    	
    	Trigger trigger2 = TriggerBuilder
		.newTrigger()
		.withIdentity("dummyTriggerName2", "group1")
		.withSchedule(
			CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
		.build();
    	
    	Trigger trigger3 = TriggerBuilder
		.newTrigger()
		.withIdentity("dummyTriggerName3", "group1")
		.withSchedule(
			CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
		.build();
    	
    	Scheduler scheduler = new StdSchedulerFactory().getScheduler();

    	scheduler.start();
    	scheduler.scheduleJob(jobA, trigger1);
    	scheduler.scheduleJob(jobB, trigger2);
    	scheduler.scheduleJob(jobC, trigger3);
    
    }
}

Output


Job A is runing //every 5 seconds
Job B is runing
Job C is runing
Job A is runing //every 5 seconds
Job B is runing
Job C is runing

2. Quartz XML Example

The equivalent version in XML file. Make sure “quartz.properties” and “quartz-config.xml” are located at project classpath.

File – quartz.properties


org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 3
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
org.quartz.plugin.jobInitializer.class =org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin 
org.quartz.plugin.jobInitializer.fileNames = quartz-config.xml 
org.quartz.plugin.jobInitializer.failOnFileNotFound = true

File – quartz-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<job-scheduling-data
	xmlns="http://www.quartz-scheduler.org/xml/JobSchedulingData"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.quartz-scheduler.org/xml/JobSchedulingData 
        http://www.quartz-scheduler.org/xml/job_scheduling_data_1_8.xsd"
	version="1.8">

	<schedule>
		<job>
			<name>JobA</name>
			<group>GroupDummy</group>
			<description>This is Job A</description>
			<job-class>com.mkyong.quartz.JobA</job-class>
		</job>

		<trigger>
			<cron>
				<name>dummyTriggerNameA</name>
				<job-name>JobA</job-name>
				<job-group>GroupDummy</job-group>
				<!-- It will run every 5 seconds -->
				<cron-expression>0/5 * * * * ?</cron-expression>
			</cron>
		</trigger>
	</schedule>
	
	<schedule>
		<job>
			<name>JobB</name>
			<group>GroupDummy</group>
			<description>This is Job B</description>
			<job-class>com.mkyong.quartz.JobB</job-class>
		</job>

		<trigger>
			<cron>
				<name>dummyTriggerNameB</name>
				<job-name>JobB</job-name>
				<job-group>GroupDummy</job-group>
				<!-- It will run every 5 seconds -->
				<cron-expression>0/5 * * * * ?</cron-expression>
			</cron>
		</trigger>
	</schedule>
</job-scheduling-data>

File : web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
<listener>
    <listener-class>
       org.quartz.ee.servlet.QuartzInitializerListener
   </listener-class>
</listener>
</web-app>

3. Spring Example

The equivalent version in Spring.


package com.mkyong.job;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class JobA extends QuartzJobBean {

	@Override
	protected void executeInternal(JobExecutionContext arg0)
		throws JobExecutionException {
		System.out.println("Job A is runing");
	}

}

package com.mkyong.job;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class JobB extends QuartzJobBean {

	@Override
	protected void executeInternal(JobExecutionContext arg0)
		throws JobExecutionException {
		System.out.println("Job B is runing");
		
	}

} 
 
package com.mkyong.job;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class JobC extends QuartzJobBean {

	@Override
	protected void executeInternal(JobExecutionContext arg0)
		throws JobExecutionException {
		System.out.println("Job C is runing");
		
	}

}

File : Spring-Quartz.xml – Declares jobs and triggers in Spring XML bean configuration file.


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="jobA" class="com.mkyong.job.JobA" />
	<bean id="jobB" class="com.mkyong.job.JobB" />
	<bean id="jobC" class="com.mkyong.job.JobC" />

	<!-- Quartz Job -->
	<bean name="JobA" class="org.springframework.scheduling.quartz.JobDetailBean">
		<property name="jobClass" value="com.mkyong.job.JobA" />
	</bean>

	<bean name="JobB" class="org.springframework.scheduling.quartz.JobDetailBean">
		<property name="jobClass" value="com.mkyong.job.JobB" />
	</bean>
	
	<bean name="JobC" class="org.springframework.scheduling.quartz.JobDetailBean">
		<property name="jobClass" value="com.mkyong.job.JobC" />
	</bean>
	
	<!-- Cron Trigger, run every 5 seconds -->
	<bean id="cronTriggerJobA" 
                class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail" ref="JobA" />
		<property name="cronExpression" value="0/5 * * * * ?" />
	</bean>
	
	<bean id="cronTriggerJobB" 
                class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail" ref="JobB" />
		<property name="cronExpression" value="0/5 * * * * ?" />
	</bean>
	
	<bean id="cronTriggerJobC" 
                class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail" ref="JobC" />
		<property name="cronExpression" value="0/5 * * * * ?" />
	</bean>

	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="cronTriggerJobA" />
				<ref bean="cronTriggerJobB" />
				<ref bean="cronTriggerJobC" />
			</list>
		</property>
	</bean>

</beans>

Run it


package com.mkyong.common;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
	public static void main(String[] args) throws Exception {
		new ClassPathXmlApplicationContext("Spring-Quartz.xml");

	}
}

Output.


INFO: Starting beans in phase 2147483647
Jul 30, 2012 10:38:13 PM org.springframework.scheduling.quartz.SchedulerFactoryBean startScheduler
INFO: Starting Quartz Scheduler now
Job A is runing
Job B is runing
Job C is runing
Job A is runing
Job B is runing
Job C is runing

Download Source Code

References

  1. Using Quartz with Spring

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
22 Comment threads
4 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
24 Comment authors
Rohini RajaramMadhuri InugantiAnand JOisReddySebastiano Recent comment authors
newest oldest most voted
Rohini Rajaram
Guest
Rohini Rajaram

I think we are missing a basic point here – to satisfy the need for a centralized scheduler, we are putting multiple batch jobs in one JVM process. For resource intensive jobs which is the case in most PROD environments, following the above style of running all batches as a part of the same JVM process can be disastrous.

Anand JOis
Guest
Anand JOis

This examples best suits for my work but the problem is all jobs run at the same time. I want to run the job one by one. Is there any way using quartz scheduler?

Thanks
Anand

tp
Guest
tp

Hi Mkyong.
Can we use multiple properties file for separate customers.? If so how to load them up?

Elyon
Guest
Elyon

hi i have been trying to run multiple triggers in a single job this is my question at stackoverflow http://stackoverflow.com/questions/27893532/single-job-with-multiple-triggers-quartz-groovy .but only the first triggers is getting called when it runs for the next trigger with the same job it gives the following error :error :org.quartz.ObjectAlreadyExistsException: Unable to store Job : ‘Group1.JobName’, because one already exists with this identification. should i assign new group and job name to the job everytime ? please let me know how to approach the problem at the link

macDaddy
Guest
macDaddy

Good afternoon mkyong ,
i want to implement quartz scheduler with mysql DB.
could you please help me.

knyala
Guest
knyala

Thanks for post..
I followed Quartz xml configuration to do a POC and made it successfully. But can we pass cron expression to quartz-config.xml from a property file?

Sebastiano
Guest
Sebastiano

Have you found any solution?

Reddy
Guest
Reddy

hi ,did u found solution for this

Yanni Green
Guest
Yanni Green

Hi mkyong,
I want to add a job to the running quartz
scheduler instance.
I am looking to be able to schedule
jobs “dynamically” via adding/removing entries to a sql tables. I don’t want to statically
hard code jobs into my application code.
And i want able to add triggers to job dynamically
can you plean give me some exemple
Thanks

Madhuri Inuganti
Guest
Madhuri Inuganti

Did you find a solution for this. I have same requirement.

Oliver
Guest
Oliver

Hello mkyong! Great article!!!
I’m using the Quartz XML example and trying to set the cron timer programaticaly. Do you have any sugestion on how should I do it?

Thanks in advance!

Rajeev
Guest
Rajeev

Hi
I new to quartz so need some input fro you on that. I have requirement where i need to schedule and start my job class from an EJB. I am able to start the scheduler in the @startup bean, My question here is that is it okie to schedule a quartz job from a Stateless Session Bean?

Lakshmi
Guest
Lakshmi

Hi Mkyong,

Thank You for your wonderful post.
can you please let me know how to stop executing job(if we want to stop jon running) using

Quartz XML Example.
Please do reply.

Suhas
Guest
Suhas

The line gives me error is this.
JobDetail jobA = JobBuilder.newJob(JobA.class)
.withIdentity(jobKeyA).build();

and the error is

Exception in thread “main” java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.quartz.impl.StdSchedulerFactory.(StdSchedulerFactory.java:274)
at Scheduler1.main(Scheduler1.java:48)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
… 2 more

nothing seems to be fixing this issue..any help?

David
Guest
David

u will need to add below jar to the pom.xml:

org.slf4j
slf4j-api
1.6.1

Hari
Guest
Hari

How can we use one Job class to execute more than one different jobs to be triggered at different times?

Nicolas
Guest
Nicolas

Hi, if I have to schedule three jobs that are triggered at different times, should I have three different schedulers?

uqk
Guest
uqk

Is it possible to use/call quartz.properties and quartz-config.xml using only plain java (main method)…? Without Spring/servlet/web environment

Israfil Mondal
Guest
Israfil Mondal

Can i start quartz jobs start in time of deployment of (Project)war file.And thank you very much for “this multiple jobs run at a time” code examples……

Please clarify automatically quartz jobs start possible without calling this……Plzzz

clarify…………………tk..cr…:)

Israfil Mondal
Guest
Israfil Mondal

Thanks…………a lots

Nirdesh Mani
Guest
Nirdesh Mani

Yes,you are right.We can’t associate multiple jobs with the same trigger (a given job can have multiple triggers, but not vice versa).

Souza
Guest
Souza

Good afternoon mkyong ,

I need to outsource in a properties file the cron settings,

For example, if I change the properties, it would reflected on the runtime from cron settiings in a properties, could you help me, please?

G. Kinu
Guest
G. Kinu

Hi. Which libraries are you using? quartz1.8.4 and 2.1.6 are complaining about the @Override in job definition classes.

parag
Guest
parag

hi can you show me how to start job using SchedulerFactoryBean ie also by creating job and trigger pragmatically instead of defining it in config.xml file. ( In spring-3.1 above )

Huy
Guest
Huy

So clearly impression

trackback
How to trigger a Quartz job manually (JSF 2 example)

[…] Multiple jobs in Quartz This article is under – JSF 2 Tutorials , Tags : jsf2 quartz scheduler mkyong Founder and Chief Editor of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. […]