Scheduling a Quartz job - java

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()

Related

This job run every 20s but noting saved in database, on the first time after first run the batch work but after that although the job is running

package com.wombatrack.configBatch;
import com.wombatrack.domain.entites.UserInstagram;
import com.wombatrack.service.UserInstagramService;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableBatchProcessing
public class BatchConfig {
#Bean
ItemReader<UserInstagram> restUserInstagramReader(UserInstagramService userInstagramService) {
return new RESTUserInstagramReader(userInstagramService);
}
#Bean
ItemProcessor<UserInstagram, UserInstagram> restUserInstagramProcessor() {
return new LoggingUserInstagramProcessor();
}
#Bean
ItemWriter<UserInstagram> restUserInstagramWriter() {
return new LoggingUserInstagramWriter();
}
#Bean
Step restUserInstagramStep(ItemReader<UserInstagram> restUserInstagramReader,
ItemProcessor<UserInstagram, UserInstagram> restUserInstagramProcessor,
ItemWriter<UserInstagram> restUserInstagramWriter,
StepBuilderFactory stepBuilderFactory) {
return stepBuilderFactory.get("restUserInstagramStep")
.<UserInstagram, UserInstagram>chunk(5)
.reader(restUserInstagramReader)
.processor(restUserInstagramProcessor)
.writer(restUserInstagramWriter)
.allowStartIfComplete(true)
.build();
}
#Bean
Job restUserInstagramJob(JobBuilderFactory jobBuilderFactory,
#Qualifier("restUserInstagramStep") Step restUserInstagramStep) {
return jobBuilderFactory.get("restUserInstagramJob")
.incrementer(new RunIdIncrementer())
.flow(restUserInstagramStep)
.end()
.build();
}
}
I have a probleme with this peace of code my job run first time, but after that return user null that mean busness ligique of job run one time whene the application start first time
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class BatchLauncher {
#Autowired
private JobLauncher jobLauncher;
#Autowired
private Job job;
public BatchStatus run() throws JobParametersInvalidException, JobExecutionAlreadyRunningException,
JobRestartException, JobInstanceAlreadyCompleteException {
JobParameters parameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
.toJobParameters();
JobExecution jobExecution = jobLauncher.run(job, parameters);
return jobExecution.getStatus();
}
}
** I put a schedular that will run every 20 seconds the job runs after every 20 seconds as expected, but the problem is that the business, i.e. the backup at the database level does not work no effect.
the job does its role only the first time after the application is started in the first time, but after that the scheduler makes the job run every 20 seconds but the information is not saved, I have a return every time the job with status COMPLETED but the job does nothing in terms of saving new data**
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
#Component
#Slf4j
public class Schedular {
#Autowired
private BatchLauncher batchLauncher;
#Scheduled(fixedDelay = 20000)
public void perform() throws Exception {
log.info("Batch programmé pour tourner toutes les 20 secondes");
batchLauncher.run();
}
}
**I don't have any idea how to do it to fix this problem, i debug application but
I did not find any solution Please if someone can help me **

Multiple quartz Schedulers for multiple threads

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

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);
/* ... */

Schedule a task to run at everyday on a specific time

I am trying to execute specific work in my Servlet/JSP application in everyday at 8.00AM and 12.00 PM. The Quartz library seems to be ideal for this, so I tried using it.
I used both of the tutorials and examples in below links.
http://www.mkyong.com/java/quartz-2-scheduler-tutorial/
http://www.javacodegeeks.com/2012/07/quartz-2-scheduler-example.html
Below is an attempt
Job class
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job
{
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("Hello Quartz!");
}
}
Trigger class
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class SimpleTriggerExample {
public static void main(String[] args) throws Exception {
JobDetail job = JobBuilder.newJob(HelloJob.class)
.withIdentity("dummyJobName", "group1").build();
// Trigger the job to run on the next round minute
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("dummyTriggerName", "group1")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(5).repeatForever())
.build();
// schedule it
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}
However, both are not satisfying my need. They do not run at specific time. How can I use the Quarts to execute the job everyday 8.00AM and 12.00 PM?
Try create a schedule with Cron:
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("triggerName","triggerGroup")
.withSchedule(CronScheduleBuilder.cronSchedule("0 0 12 * * ?")).build();
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("triggerName","triggerGroup")
.withSchedule(CronScheduleBuilder.cronSchedule("0 0 8 * * ?")).build();
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("triggerName","triggerGroup")
.withSchedule(CronScheduleBuilder.cronSchedule("0 30 12 * * ?")).build(); //schedules a job for 12:30am
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("triggerName","triggerGroup")
.withSchedule(CronScheduleBuilder.cronSchedule("0 0 14 * * ?")).build(); //schedules a job for 2pm
Use this site for great information on scheduling:
http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("reportTrigger").WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(23,0)).Build();

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

Categories

Resources