Multiple quartz Schedulers for multiple threads - java

I want to create multiple threads on Java, and allot each thread a separate Quartz scheduler. But the only way I can find is to create multiple .properties files, for each separate scheduler. As I have a huge number of threads, creating so many properties files isn't feasible. Is there a better way to do so?

Please use this concept to handle multiple scheduler threads for multiple task on the basis of dynamic parameter
/*
* Date : 2015-07-06
* Author : Bhuwan Prasad Upadhyay
*/
package com.developerbhuwan.quartzexample;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
/**
*
* #author developerbhuwan
*/
public class MutlipleScheduleThread {
public static void main(String[] args) {
new MutlipleScheduleThread().createMultipleThread();
}
private void createMultipleThread() {
for (int i = 0; i <= 10; i++) { //create 10 scheduler thread to perform different job on the basis of param
try {
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put(MyJob.KEY_PARAM, "ParamValue");
JobKey jobKey = new JobKey("UniqueJobId" + i, "JobGroup");
JobDetail job = JobBuilder
.newJob(MyJob.class)
.withIdentity(jobKey)
.setJobData(jobDataMap)
.storeDurably(true)
.build();
TriggerKey triggerKey = new TriggerKey("UniqueTriggerID" + i, "TriggerGroup");
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity(triggerKey)
.withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 1/1 * ? *")) //every one hour
.forJob(job)
.build();
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException ex) {
Logger.getLogger(MutlipleScheduleThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private static class MyJob implements Job {
private static String KEY_PARAM = "param";
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
String param = dataMap.getString(KEY_PARAM);
//do job on the basis of parameter
}
}
}
Source Code Quartz Example

Related

How to design Quartz Scheduler in Weblogic with Dynamic Cron Job that changes at runtime?

I'm using Quartz in stand alone jar. Added that in SET ENV PRE_CLASSPATH of Weblogic 12.2.1.3. Configured Startup Class. Cron parameter is dynamically passed from a DB Table. Till that it is fine. But I want to change the cron parameter in db table so that Quartz takes that and changes the schedule timing dynamically AT RUNTIME itself. Problem is, I have to restart weblogic to take that effect. Because Quartz is checking the DB parameter at server start time only. How to get that working in real time?
package com.adac.scheduler.service;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class QuartzFTPPush implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("This is a Job That is Scheduled At "+new Date());
}
}
package com.adac.scheduler.service;
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;
import org.quartz.impl.matchers.KeyMatcher;
import java.sql.*;
public class QuartzFTPPushCronTrigger {
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:AGPOS/yed6_4aN#10.6.6.11:1532:AGPTST");
Statement stmt=con.createStatement();
//ResultSet rs=stmt.executeQuery("SELECT DB_HOST, DB_PORT, DB_USERNAME, DB_PASSWORD, DB_SID, DB_TABLE from AG_RSD_SCHEDULE_MAS_TBL");
ResultSet rs = stmt.executeQuery("Select cron_schedule from AG_RSD_SCHEDULE_MAS_TBL where company_id=5");
/*
* while(rs.next())
* System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
*/
rs.next();
String cron_schedule = rs.getString(1);
con.close();
final JobKey jobKey = new JobKey("QuartzFTPPushName", "group1");
final JobDetail job = JobBuilder.newJob(QuartzFTPPush.class).withIdentity(jobKey).build();
//final String cron_schedule = "0/5 * * * * ?";
//final Trigger trigger = TriggerBuilder.newTrigger().withIdentity("QuartzFTPPushTriggerName", "group1").withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")).build();
final Trigger trigger = TriggerBuilder.newTrigger().withIdentity("QuartzFTPPushTriggerName", "group1").withSchedule(CronScheduleBuilder.cronSchedule(cron_schedule)).build();
final Scheduler scheduler = new StdSchedulerFactory().getScheduler();
// Listener attached to jobKey
scheduler.getListenerManager().addJobListener(new QuartzFTPPushListener(), KeyMatcher.keyEquals(jobKey));
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}
package com.adac.scheduler.service;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
public class QuartzFTPPushListener implements JobListener {
public String getName() {
return "QuartzFTPPushListener";
}
public void jobToBeExecuted(JobExecutionContext context) {
final String jobName = context.getJobDetail().getKey().toString();
System.out.println("jobToBeExecuted: " + jobName + " is starting...");
}
public void jobExecutionVetoed(JobExecutionContext context) {
System.out.println("jobExecutionVetoed");
}
public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
System.out.println("jobWasExecuted");
final String jobName = context.getJobDetail().getKey().toString();
System.out.println("Job : " + jobName + " is finished!!");
if (!jobException.getMessage().equals("")) {
System.out.println("Exception thrown by: " + jobName + " Exception: " + jobException.getMessage());
}
}
}
Select cron_schedule from "AG_RSD_SCHEDULE_MAS_TBL" where company_id=5;
The output of above query is 0/10 * * * * ?. I want to change that to some other value, let's say 0/5 * * * * ?. And want Quartz to schedule with same without restarting weblogic.
Please suggest.

How to start a Job with several cron-triggers using the quartz-scheduler?

I'm using the Quartz Scheduler to start jobs in my Java-App. I have the job HelloJob.java
package com.stackoverflow.test.java;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job {
private String message;
public HelloJob() {
Date akt = new Date();
this.message = "Quartz is running (" + akt + ").";
}
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println(this.message);
}
}
I'd like to start this job using two different cron expressions (here: */5 */3 * * * ? and */9 */2 * * * ?). I tried the following:
package com.stackoverflow.test.java;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.JobBuilder;
import org.quartz.CronScheduleBuilder;
public class TestQuartz {
public static void main(String[] args) {
try {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
/* ################################################################### */
JobDetail job = JobBuilder
.newJob(HelloJob.class)
.withIdentity("job1", "group1")
.build();
CronScheduleBuilder sb1 = CronScheduleBuilder
.cronSchedule("*/5 */3 * * * ?");
CronScheduleBuilder sb2 = CronScheduleBuilder
.cronSchedule("*/9 */2 * * * ?");
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(sb1)
.build();
Trigger trigger2 = TriggerBuilder
.newTrigger()
.withIdentity("trigger2", "group1")
.startNow()
.withSchedule(sb2)
.build();
scheduler.scheduleJob(job, trigger);
scheduler.scheduleJob(job, trigger2);
/* ################################################################### */
Thread.sleep(10 * 60 * 1000);
System.out.println("FIN");
/* ################################################################### */
scheduler.shutdown();
} catch (SchedulerException se) {
se.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I receive the following exception:
org.quartz.ObjectAlreadyExistsException: Unable to store Job : 'group1.job1', because one already exists with this identification.
at org.quartz.simpl.RAMJobStore.storeJob(RAMJobStore.java:279)
at org.quartz.simpl.RAMJobStore.storeJobAndTrigger(RAMJobStore.java:251)
at org.quartz.core.QuartzScheduler.scheduleJob(QuartzScheduler.java:886)
at org.quartz.impl.StdScheduler.scheduleJob(StdScheduler.java:249)
at com.stackoverflow.test.java.TestQuartz.main(TestQuartz.java:47)
Is it impossible to start one Job with several triggers? Can I somehow generate a schedule that considers more than one cron expression?
You have to use TriggerBuilder's forJob(JobKey jobKey) method to assign further triggers to a job.
Trigger trigger = TriggerBuilder.newTrigger().forJob(job.getKey()). ...
scheduler.scheduleJob(trigger)
In your case, apply the following modifications:
/* ... */
Trigger trigger2 = TriggerBuilder
.newTrigger()
.forJob(job.getKey())
.withIdentity("trigger2", "group1")
.startNow()
.withSchedule(sb2)
.build();
/* ... */
scheduler.scheduleJob(trigger2);
/* ... */

Scheduling a Quartz job

I want to develop a quartz job which will run on a particular time specified within the job. But while I am starting the job it starts at that time not on that time which is specified within the code.
Please help.
Here is my code:
import java.util.TimeZone;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class CronScheluderForActivityMilestone {
public boolean CronScheluderForActivityMilestone() throws Exception {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sche = sf.getScheduler();
sche.start();
JobDetail jDetail = new JobDetail("SendMailOnActivityMileStone", "SendMailOnActivityMileStone", ActivityMileStoneSendMail.class);
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("mytriggerForActivityMileStone", "SendMailOnActivityMileStone")
.withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(19, 00).inTimeZone(TimeZone.getTimeZone("Asia/Calcutta")))
.forJob("SendMailOnActivityMileStone", "SendMailOnActivityMileStone")
.build();
sche.scheduleJob(jDetail, trigger);
return true;
}
}
You should change your inTimeZone configuration like this :
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger3", "group1")
.withSchedule(weeklyOnDayAndHourAndMinute(DateBuilder.WEDNESDAY, 10, 42)
.inTimeZone(TimeZone.getTimeZone("America/Los_Angeles")))
.forJob(job)
.build();
inTimeZone belongs to withSchedule()

java quartz scheduler run at specific time

For example, I want to write a Java program to print "Hello World" at each day 12 am, how can I use Quartz scheduler to achieve this?
Trigger trigger = TriggerUtils.makeDailyTrigger(0, 0);
trigger.setName("trigger1");
trigger.setGroup("group1");
Like this? Where should I put print "hello world" method?
You could use an expression to schedule the execution of the job. e.g.:
public static class HelloJob implements Job {
#Override
public void execute(JobExecutionContext ctx) throws JobExecutionException {
System.out.println("Hello World");
}
}
public static void main(String[] args) throws SchedulerException {
String exp = "0 0 0 1/1 * ? *";
SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = factory.getScheduler();
scheduler.start();
JobDetail job = JobBuilder.newJob(HelloJob.class).build();
Trigger trigger = TriggerBuilder.newTrigger()
.startNow()
.withSchedule(
CronScheduleBuilder.cronSchedule(exp))
.build();
scheduler.scheduleJob(job, trigger);
}
See http://www.cronmaker.com/ for build another expression. e.g. 0 0/1 * 1/1 * ? * every minute for to see the output. See also Cron Expressions.
Download quartz Jar Put in lib folder build project
Create Class (Job) from which you want to schedule task
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class MyJob implements Job {
private Logger log = Logger.getLogger(MyJob.class);
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
log.debug("Hi....");
System.out.println("Corn Executing.....");
}
}
Create Class for schedule your task
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class JobScheduler {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("myjob").build();
Trigger trigger = TriggerBuilder.newTrigger().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(30).repeatForever()).build();
SchedulerFactory schFactory = new StdSchedulerFactory();
Scheduler scheduler = schFactory.getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}catch (SchedulerException e) {
e.printStackTrace();
}
}
}
You have to create your custom job by implementing Job interface and providing your implementation of execute method.In execute method you can print "hello world". Then you can schedule your job like this
scheduler.scheduleJob(job, trigger);
Refer this link for step by step details:
Quartz tutorial
you can create cron expression for this. to have quartz job you need to have following objects
Job
Task which will be associated to a Job
Finally create a trigger and associate a Job to the trigger
Triggers of two type
Simple triggers, where you can control job , you can run every min or 10 mins and so on. you can also have additional parameters
initial delay - to kick off
repeatcount - no of times the job should be executes, if -1 then job will be executed infinitely
In your case you can use cron triggers since you want to run every day at 12 am.
For more details and sample program look at this below link
http://www.mkyong.com/spring/spring-quartz-scheduler-example/
and about quartz cron expression , see the quartz documentation
http://quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger

Problem while executing simple quartz scheduler

I am learning quartz scheduler framework and as a base I have started with "Hello World" thats prints at regular Intervals.
This is my SampleScheduler
public class SampleScheduler {
public static void main(String arfs[]) {
try {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
System.out.println("Scheduler Started...");
JobDetail job = new JobDetail("job1","group1",SampleJobInter.class);
Trigger trigger = new SimpleTrigger("trigger1",Scheduler.DEFAULT_GROUP,new Date(),null,SimpleTrigger.REPEAT_INDEFINITELY,60L*1000L);
scheduler.scheduleJob(job, trigger);
scheduler.shutdown();
System.out.println("Scheduler Stopped..");
} catch(SchedulerException e) {
}
}
}
Here is my SampleJobInter.class
public class SampleJobInter implements Job {
SampleJobInter(){}
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
// TODO Auto-generated method stub
System.out.println("Hello World at "+new Date());
}
}
The output am getting is
Scheduler Started...
Scheduler Stopped..
I am not getting the desired output. I am running it in the console. Do I need to do any configurations or what?. Please Help me in this
just put scheduler.start() after you have scheduled a job to run - scheduler.scheduleJob...
UPDATE: I stand corrected by org.life.java. The order of statements won't make much of a difference. The source of your troubles is the shutdown() invocation. A scheduler's contract [javadoc] is to keep running as long as an explicit shutdown command is not issued on it. if you remove that line from your code, it works fine.
I have created it from scratch and it works well.!!
I would suggest you to compare your code with this ans also log exception in catch so that you will have good idea.
JobRunner
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.life.java.so.questions;
/**
*
* #author Jigar
*/
import java.util.Date;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
public class HelloSchedule {
public HelloSchedule() throws Exception {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
sched.start();
JobDetail jd = new JobDetail("myjob", sched.DEFAULT_GROUP, SampleJobInter.class);
SimpleTrigger st = new SimpleTrigger("mytrigger", sched.DEFAULT_GROUP, new Date(),
null, SimpleTrigger.REPEAT_INDEFINITELY, 100L);
sched.scheduleJob(jd, st);
}
public static void main(String args[]) {
try {
new HelloSchedule();
} catch (Exception e) {
}
}
}
Job
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.life.java.so.questions;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
*
* #author Jigar
*/
public class SampleJobInter implements Job {
public SampleJobInter() {
}
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("Hello World at " + new Date());
}
}

Categories

Resources