Main Tutorials

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 Author

author image
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

Subscribe
Notify of
27 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Rohini Rajaram
6 years ago

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
6 years ago

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
9 years ago

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

Elyon
9 years ago

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

Raja
5 days ago
Reply to  Elyon

do you get any answer ?

macDaddy
9 years ago

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

knyala
9 years ago

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?

Reddy
8 years ago
Reply to  knyala

hi ,did u found solution for this

Sebastiano
9 years ago
Reply to  knyala

Have you found any solution?

Yanni Green
9 years ago

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

Sameer Pande
2 years ago
Reply to  Yanni Green

I have found a solution for this. We can make use of dynamic class creation which can compile and load job at runtime. My job creation would require only one use case but you can change it.

https://stackoverflow.com/questions/2320404/creating-classes-dynamically-with-java

Madhuri Inuganti
6 years ago
Reply to  Yanni Green

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

Oliver
9 years ago

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
10 years ago

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
10 years ago

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
10 years ago

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
9 years ago
Reply to  Suhas

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

org.slf4j
slf4j-api
1.6.1

Hari
10 years ago

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

Nicolas
10 years ago

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

uqk
10 years ago

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
10 years ago

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…:)

Nirdesh Mani
11 years ago

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
11 years ago

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?

parag
11 years ago

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
11 years ago

So clearly impression

Israfil Mondal
10 years ago

Thanks…………a lots

G. Kinu
11 years ago

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