Quartz scheduler executes jobExecuted method for each repeat trigger - java

This is a job scheduler code
JobDetail job = JobBuilder.newJob()
.ofType( AppJob.class )
.withIdentity("id", "jobgroup")
.setJobData(jobDataMap)
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger_id", "jobGroup")
.startAt( start.getTime() )
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(1).repeatForever())
.endAt( end.getTime() )
.build();
And the listener
scheduler.getListenerManager().addJobListener(new JobListener() {
#Override
public String getName() {
return "ffdfd";
}
#Override
public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {
}
#Override
public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
}
#Override
public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException e) {
System.out.println(" fdfnkdfkndfnkldnnl OVERRR ");
}
}, KeyMatcher.keyEquals(jobKey(String.valueOf(id), "jobGroup")));
As this is the repeated event, the jobWasExecuted method executes every time for the repeat interval
How to get one final complete event for this job

Related

how to cancel the time scheduled cron job in java?

public class CronTriggerApp {
public static void main(String[] args) {
try {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();
JobDetail job = JobBuilder.newJob(Main.class)
.withIdentity("dummyJobName", "group1").build();
System.out.println(job);
Date startTime = DateBuilder.nextGivenSecondDate(null, 5);
System.out.println(startTime);
// run every 20 seconds infinite loop
CronTrigger crontrigger = TriggerBuilder
.newTrigger()
.withIdentity("TwentySec", "group1")
.startAt(startTime)
.startNow()
.withSchedule(CronScheduleBuilder.cronSchedule("* * * ? * *"))//0 53 12 * * ? *
.build();
scheduler.start();
scheduler.scheduleJob(job, crontrigger);
//scheduler.shutdown();
} catch (SchedulerException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Main implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException
{
System.out.println("Trigger Starts.."+new Date());
System.out.println("ALL_OFF");
}
}
By using above code i can able to schedule cron job..but if want cancel the schedule time how can able to cancel or stop the schedule task?
can any one plz help me how can i stop or cancel the scheduled task?
You can expose an endpoint to interrupt it. And use the following function of scheduler to stop it.
            
scheduler.interrupt(jobDetail.getKey());

Quartz CronScheduler running job multiple times

I am using Quartz CronScheduler to execute a job every 15 minutes. Every time the job executes it checks the DB for any change in the cron expression and updates the job scheduler for the next run. I have implemented the above in the following way:
#Service
public class QuartzSchedulerService {
private static final Logger LOG = LoggerFactory.getLogger(QuartzSchedulerService.class);
private Scheduler scheduler;
#PostConstruct
private void init() {
try {
scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
} catch (Exception e) {
LOG.error("Unable to start quartz scheduler", e);
}
}
#PreDestroy
private void destroy() {
try {
scheduler.shutdown();
} catch (Exception e) {
LOG.error("Unable to shutdown quartz scheduler", e);
}
}
public void registerCronJob(Class<? extends Job> jobClass, String cronExpression) {
try {
String jobName = jobClass.getSimpleName();
CronScheduleBuilder cronBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName).build();
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName).withSchedule(cronBuilder).build();
scheduler.scheduleJob(jobDetail, cronTrigger);
LOG.info("Registered Cron Job:" + jobName + " " + jobDetail.getKey());
} catch (Exception e) {
LOG.error("Unable to register cron job", e);
}
}
public void updateCronSchedule(Class<? extends Job> jobClass, String cronExpression) {
try {
String jobName = jobClass.getSimpleName();
CronScheduleBuilder cronBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
CronTrigger newCronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName).withSchedule(cronBuilder).build();
scheduler.rescheduleJob(TriggerKey.triggerKey(jobName), newCronTrigger);
LOG.info("Updated Cron Job:" + jobName + " " + newCronTrigger.getJobKey());
LOG.info("Jobs executed: " + scheduler.getMetaData().getNumberOfJobsExecuted());
} catch (Exception e) {
LOG.error("Unable to reschedule cron job", e);
}
}
}
The class which implements the Job interface is as belows:
#Component
#DisallowConcurrentExecution
public class PropertiesReloadJob implements Job {
private static final Logger LOG = LoggerFactory.getLogger(PropertiesReloadJob.class);
#Autowired
private QuartzSchedulerService schedulerService;
#Autowired
private PropertiesService propertiesService;
public void loadAtStartup() {
load();
LOG.info("--- Registerting PropertiesReload Cron Job ---");
schedulerService.registerCronJob(PropertiesReloadJob.class, propertiesService.getCacheReloadCronExpression());
}
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
load();
LOG.info("--- Updating Pro Cron Job ---");
schedulerService.updateCronSchedule(PropertiesReloadJob.class, propertiesService.getCacheReloadCronExpression());
}
public void load(){
// Load properties from DB
}
The loadAtStartup() method is called during context initializtion and then after every 15 minutes the execute() method is called.
The cron expression used is: 0 0/15 * 1/1 * ? *
Now, the problem is as follows:
Lets say that the job starts at 3:00:00, it will execute as many times it can till 3:00:01, rather than executing only once.
Next the job will start at 3:15:00 and again will run as many times it can till 3:15:01.
The number of times the job executes is different every time.
I am not sure what is causing this behaviour. I have tested the cron expression with cronmaker.
Can somebody point out the error here ?

How To implement Quartz Scheduler in server side? What all are the steps i want to do?

public static void setupSchedule() {
try {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();
JobDetail job = newJob(Reader.class).withIdentity("job1", "group1").build();
String Frequency = Props.getProps().getProperty("BIRTHDAYFREQUENCY");
CronTrigger ct = newTrigger().withIdentity("trigger1", "group1")
.withSchedule(cronSchedule(Frequency)).build();
scheduler.scheduleJob(job, ct);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
If you are asking to implement quartz scheduler in web application then answer is yes.
All you have to do put all scheduler configuration in servlet init method. Like you have done it your question. Init method will be called only once on start-up of application or on first request. So all the configuration and scheduler time will be set at that time. Make sure to include all the quartz dependencies.
private Scheduler scheduler ;
public void init(ServletConfig config) throws ServletException
{
JobKey jobKeyA = new JobKey("jobA", "group1");
JobDetail jobA = JobBuilder.newJob(CallJob.class)
.withIdentity(jobKeyA).build();
//jobA.getJobDataMap().put("queue_setup", queue_setup);
Trigger trigger1 = TriggerBuilder
.newTrigger()
.withIdentity("triggerJobA", "group1")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInMinutes(1).repeatForever()).build();
//runs every minute
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(jobA, trigger1);
}
Job class
public class CallJob implements Job {
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException
{
System.out.println("Yes job is running");
}
}

Is possible to postpone trigger fire in Quartz?

I have two processes:
Process 1 - implements runnable and can run forever.
Process 2 - fires at fixed hour and minute of day (i've created a job that run with Quartz).
To warn the process 1 that the other process is running I can use the TriggerListener, but how can I postpone the fire of the second process if the process 1 still doing something?
For example: I need to fire the trigger at 2PM, but this need to be done after 2PM if the process 1 isnt idle.
Here's some sample:
ProcessForever.java
import static org.quartz.CronScheduleBuilder.dailyAtHourAndMinute;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
public class ProcessForever implements Runnable {
private boolean processTwoRunning;
private Scheduler scheduler;
private Trigger trgProcessTwo;
private String status;
public static final STATUS_PROCESS = "PROCESS";
public static final STATUS_SLEEP = "SLEEP";
private static Logger LOGGER = Logger.getLogger( ProcessForever.class.getName() );
public void init() throws SchedulerException {
SchedulerFactory fact = new StdSchedulerFactory();
scheduler = fact.getScheduler();
}
#Override
public void run() {
try {
scheduler.start();
buildTrigger();
while( true ) {
//do something and then sleep for some time.
//the Quartz trigger should fire only in STATUS_SLEEP...
setStatus( STATUS_PROCESS );
try { Thread.sleep(120 * 1000); }catch(Exception e){}
setStatus( STATUS_SLEEP );
}catch( Exception e ) {
e.printStackTrace();
}
}
private void buildTrigger() throws SchedulerException {
LOGGER.info("defineCargaDadosTrigger()");
JobDetail dt = newJob( ProcessTwo.class )
.withIdentity("coleta","grpcoleta")
.build();
trgProcessTwo = newTrigger().withIdentity(
new TriggerKey("triggerProcessTwo") )
.forJob( dt )
.startNow()
.withSchedule( dailyAtHourAndMinute(13,31) )
.build();
KeyMatcher<TriggerKey> m = KeyMatcher.keyEquals( trgProcessTwo.getKey() );
scheduler.scheduleJob(dt, trgProcessTwo );
//this will notice the process 1 that the trigger is running...
//scheduler.getListenerManager().addTriggerListener(someclass, m );
}
//getters & setters ommited...
}
ProcessTwo.java
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
ProcessTwo cannot run concurrent with ProcessForever...
*/
public ProcessTwo implements Job {
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("Doing something...");
try { Thread.sleep(10000); } catch( InterruptedException i ){}
System.out.println("Stop doing something...");
}
}
That's quite a common question in Quartz. Here are some hints provided by the FAQ

Service not registered on startup

I am using JBoss5.1.x AS, EJB3.0. I am trying to add a job (using Quartz) to my deployment. I am registering a new Service, so it will init the scheduler on application deploy.
My problem is that the service never gets registered when I deploy my app.
My code:
Interface:
public interface ComponentMonitoringService
{
void create() throws Exception;
void start() throws Exception;
void stop();
void destroy();
}
Service:
#Service(objectName = "com.mirs.ecms.timer:service=ServerStartupManager")
#Management(ComponentMonitoringService.class)
public class ServerStartupManager implements ComponentMonitoringService
{
private SchedulerFactory schedulerFactory = null;
private Scheduler scheduler = null;
Logger logger = Logger.getLogger("ecms.log");
public void create() throws Exception
{
}
public void start() throws Exception
{
// Write your startup code
initScheduler();
}
private void initScheduler() throws ParseException, SchedulerException
{
schedulerFactory = new StdSchedulerFactory();
scheduler = schedulerFactory.getScheduler();
JobDetail startECMSJob = new JobDetail("startECMSJob", "group1", StartECMSJob.class);
CronTrigger trigger1 = new CronTrigger("cronTrigger", "TriggersGroup1", "0 0/5 * * * ?");
scheduler.scheduleJob(startECMSJob, trigger1);
scheduler.start();
}
public void stop()
{
try
{
scheduler.shutdown();
}
catch (Exception e)
{
logger.error("ServerStartupManager Failure occured during Manager stop", e);
}
}
public void destroy()
{
}
}
I found a solution.
I was not using the right annotation. I have to use EJB3 annotations.

Categories

Resources