• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3715
  • Last Modified:

Could someone please help me with Quartz Scheduler (I'm also willing to pay for anyone who could help me run it in my application)

I want to create a Quartz Scheduler in my application so that it executes jobs on the Hourly, Daily, Weekly basis at set repetitions (eg. every 2 hours, every 2 days, every 3 weeks).  If someone could PLEASE help me this this, I'd be more than greatful and will pay for the right answer!

I went through all the available sites and wrote the code based on example files and what's written on their website but it simply doesn't work.

http://www.quartz-scheduler.org/

Please help me out here!
0
snajalm
Asked:
snajalm
  • 11
  • 10
  • 8
  • +2
1 Solution
 
for_yanCommented:
maybe I already asked this question, but  are you sure you really need Quartz Schdeduler?
What features of Quartz do you need which are not available in Timer, TimeTask classes?  
0
 
snajalmAuthor Commented:
Thanks chaituu for the two useful links.  I'll try and see if this is going to work with my code.  But I also need the set of the quartz.properties properly and make sure I'm picking the right time off gui.  I'll give this code and shot and will get back to you guys if I need any help!

for_yan:  but do you think the Timer class would be able to perform the problem statement mentioned in the question area properly without any further surprises??!! How reliable do you think it is??!  One of my application's main tasks is to schedule and run tasks.  I need to have this scheduler done by tomorrow and still got a lot to do with this app!

PLEASE HELP!
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
for_yanCommented:

there is a method of the Timer

public void schedule(TimerTask task,
                     Date firstTime,
                     long period)

so you can specify when to start the run and how often to repeat it
With the period specified - you can make this period a week or a day
or any number of hours.

I tried these options - they were working fine - I didn't try to use them for days - that is true, I tried for some minutes,
 but one can expect that they would run for days either.










0
 
snajalmAuthor Commented:
how would it be possible to define an end date with Timer so that the user can select,

start_date, end_date, every (n) hours/days/weeks

I think I'll give up with this quartz thing since I don't have time to play around with it!  
0
 
CEHJCommented:
>>How reliable do you think it is??!  

Not reliable at all. Particularly if not running as a service
0
 
for_yanCommented:
I don't think you can schedule end date froom the very brginning but you have the cancel() method for the TimerTask, so
you can read end date from the user and then chcek from time to time, say every hour and cancel those TimerTasks which are no longer necessary.
I believe, you can schedule such check as another TimerTask by the way.
 
0
 
snajalmAuthor Commented:
Would you guys have a look at the following and help me with where I'm going wrong??!  The task simply doesn't get executed at the set time!
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;

import org.quartz.DateBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *
 * @author
 */
public class IDAScheduler {
    
    int portalId;
    String portalName;
    String portalUserName;
    String portalPassword;
    String portalServerURL;
    String portalPortNumber;
    
    //Data parametes 
    int dataId;
    String txnid;
    String dataSourceSysDSN;
    String userName;
    String password;
   
    //Schedule parameters
    int scheduleId;
    String schedule_type;
    String start_date;
    String end_date;
    String starting_time;
    String repetition;
    String status; 

    public void run() throws Exception {
        //System.setProperty(StdSchedulerFactory.PROPERTIES_FILE, "/resources/quartz.properties");

        String[] startDate = start_date.split("-");
        String[] endDate = end_date.split("-");
        String[] startingTime = starting_time.split(":");
        
        //Logger log = LoggerFactory.getLogger(Schedule.class);

        //log.info("------- Initializing -------------------");

        // First we must get a reference to a scheduler
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler scheduler = sf.getScheduler();
      
        Date startTime = DateBuilder.dateOf(Integer.parseInt(startingTime[0]), 
                Integer.parseInt(startingTime[1]), Integer.parseInt(startingTime[2]), 
                Integer.parseInt(startDate[2]), Integer.parseInt(startDate[1]), 
                Integer.parseInt(startDate[0]));
        
        System.out.println("Here's the start time" + startTime);
        
        
        Date endTime = DateBuilder.dateOf(Integer.parseInt(startingTime[0]), 
                Integer.parseInt(startingTime[1]), Integer.parseInt(startingTime[2]), 
                Integer.parseInt(endDate[2]), Integer.parseInt(endDate[1]), 
                Integer.parseInt(endDate[0]));
   
        System.out.println("Here's the end time" + endTime);
        
        JobDetail job = newJob(Task.class)
            .withIdentity("job" + scheduleId, "Telechoice")           
            .build();
        
        job.getJobDataMap().put(Task.DATA_SOURCE_NAME, this.dataSourceSysDSN);
        job.getJobDataMap().put(Task.DSN_USERNAME, this.userName);
        job.getJobDataMap().put(Task.DSN_PASSWORD, this.password);
        job.getJobDataMap().put(Task.DMZ_USERNAME, this.portalUserName);
        job.getJobDataMap().put(Task.DMZ_PASSWORD, this.portalPassword);
        
        SimpleTrigger trigger = null;
        
        if (schedule_type.equals("Hourly")) {
            
            trigger = (SimpleTrigger) newTrigger() 
            .withIdentity("trigger" + scheduleId, schedule_type)
            .startAt(startTime)
                .withSchedule(simpleSchedule()
                .withIntervalInHours(Integer.parseInt(repetition))
                .withRepeatCount(scheduleId)
                .withMisfireHandlingInstructionFireNow())                
            .endAt(endTime)
            .build();
            
        } else if (schedule_type.equals("Daily")) {
            
            trigger = (SimpleTrigger) newTrigger() 
            .withIdentity("trigger" + scheduleId, schedule_type)
            .startAt(startTime)
                .withSchedule(simpleSchedule()
                .withIntervalInHours(Integer.parseInt(repetition) * 24)
                .withRepeatCount(scheduleId)
                .withMisfireHandlingInstructionFireNow())                
            .endAt(endTime)
            .build();
            
        } else if (schedule_type.equals("Weekly")) {

            trigger = (SimpleTrigger) newTrigger() 
            .withIdentity("trigger" + scheduleId, schedule_type)
            .startAt(startTime)
                .withSchedule(simpleSchedule()
                .withIntervalInHours(Integer.parseInt(repetition) * 168)
                .withRepeatCount(scheduleId)
                .withMisfireHandlingInstructionFireNow())                
            .endAt(endTime)
            .build();
            
        }
       
        
        //Date ft = sched.rescheduleJob(null, trigger) ;  //scheduleJob(job, trigger);
        scheduler.start();
        //log.info(job.getKey() +
       //         " will run at: " + ft +  
       //         " and repeat: " + trigger.getRepeatCount() + 
       //         " times, every " + trigger.getRepeatInterval() / 1000 + " seconds");
       //          
    }
      

}

Open in new window

0
 
CEHJCommented:
Can you also post the output of your debug lines please?
0
 
snajalmAuthor Commented:
Sure, here're some of them.  The application basically is supposed to make these schedules based on the Schedule objects.  So they all get read from the database into an array of Schedules containing the scheduling parameters and set up the Task.java class which then are supposed to run at thhe specified time!

Here's the start timeTue Nov 01 15:59:06 WST 2011
Here's the end timeTue Nov 22 15:59:06 WST 2011
Hourly
ScheduleID: 20
Schedule Type: Hourly
Start Date: 2011-11-01
End Date: 2011-11-08
Starting Time: 16:02:00
Reps: 1
Got here
Here's the start timeTue Nov 01 16:02:00 WST 2011
Here's the end timeTue Nov 08 16:02:00 WST 2011
Hourly
ScheduleID: 21
Schedule Type: Hourly
Start Date: 2011-11-01
End Date: 2011-11-15
Starting Time: 16:07:00
Reps: 1
Got here
Here's the start timeTue Nov 01 16:07:00 WST 2011
Here's the end timeTue Nov 15 16:07:00 WST 2011
Hourly
0
 
CEHJCommented:
I'll take a look. Use your Logger btw:


private Logger log = LoggerFactory.getLogger(IDAScheduler.class);

    public void run() throws Exception {
	if(log.isDebugEnabled()) {
	    log.debug("Start date = {}", start_date);
	}
.....

Open in new window

0
 
CEHJCommented:
scheduleJob is commented out

I would advise another cool look at your code. Include log.debug statements at all key stages, and possible one or two log.info statements (and of course log.error where necessary)
0
 
snajalmAuthor Commented:
Thanks CEHJ!  I sure will! :-)
0
 
snajalmAuthor Commented:
uh yes, but what's the difference between

scheduler.rescheduleJob(trigger.getKey(), trigger);

and

scheduler.scheduleJob(job, trigger);

0
 
snajalmAuthor Commented:
and btw, where do the logs get stored??! how can I view their contents??!
0
 
snajalmAuthor Commented:
Do you think other than the commented part, my code follows a logical behaviour compared to my initial problem statement??!
0
 
CEHJCommented:
reschedule deletes the old trigger, if there is one:

http://www.quartz-scheduler.org/api/2.1.0/org/quartz/Scheduler.html#rescheduleJob(org.quartz.TriggerKey, org.quartz.Trigger)
0
 
CEHJCommented:
>>and btw, where do the logs get stored??! how can I view their contents??!

That depends on what logging framework slf is getting bound to - what backend are you using?
0
 
CEHJCommented:
The logging thing, btw, is of paramount importance, and demands a question in its own right
0
 
snajalmAuthor Commented:
I'm not sure what you mean by the "backend"!
0
 
snajalmAuthor Commented:
It's funny, I fixed the commented out section and scheduled one of my tasks to run in a couple of minutes but nothing got fired or at least there was no output shown that would give my an indication that something's have happened!
0
 
CEHJCommented:
>>I'm not sure what you mean by the "backend"!

This is what i mean about it being of paramount importance. You need to open a separate question for this
0
 
for_yanCommented:
Try to use simple things first. If they do not work - go to the complex ones.

>>>How reliable do you think it is??!  

>>Not reliable at all. Particularly if not running as a service

Who can know how reliable it would be over many days?
I didn't run it for days. I bet CEHJ didn't run either.
And there is no reason why you cannot eventually run it as a service, if you try and it works.


And where is guarantee that Quartz - a third party software is way more reliable than part of the standard java?

With your quartz stuff - did you try first the most basic example which they provide - does it work and start the task?
Say the one pointed above tio by chaituu?
Then go from there to make it more complex to your need.
At least that is usually eaiser with new stuff.
You code is really complicated for the start.

How did you get  Quartz?

Did you download quartz-2.1.0.tar.gz from
http://terracotta.org/downloads/open-source/destination?name=quartz-2.1.0.tar.gz&bucket=tcdistributions&file=quartz-2.1.0.tar.gz ?

It looks like it is more targeted towards Unix - they don't provide zip ?
No surprise - such things probably better to run on Unix environemnt.
But you are running on windows, correct?





0
 
for_yanCommented:
Have you tried to run examples which come with Quartz - they seem to be running fine.
For example look at the Example3 - CronTriggerExample - it runs fine for me - why cannot you use it
to run your jobs?
0
 
CEHJCommented:
>>
Who can know how reliable it would be over many days?
I didn't run it for days. I bet CEHJ didn't run either.
>>

That's not why it's not reliable. The reason it's not reliable is that you don't run processes that should be daemons in user space.

Why you'd want to reinvent a scheduling framework is also beyond me...
0
 
CEHJCommented:
>>No surprise - such things probably better to run on Unix environemnt.

Quartz is written in Java. Java is platform-independent
0
 
for_yanCommented:
snajalm,
Did you finanly got it executing the Task for you from Quartz?

It works for me almost with your code
0
 
for_yanCommented:

Now have your Task executing for me every hour :)
0
 
DeepakMohanakrishnanCommented:
Apologies for late interfering in the conversation:

The code works find if the needed libraries are in place.

The only miss I found out is the jobDetail and trigger is not integrated. Please add this code before starting your scheduler:

scheduler.scheduleJob(job, trigger);

Open in new window


Hope this will work!!!
0
 
for_yanCommented:

Below is the exact code for IDAScheduler,java and Task.java
which are running for me (see output log below).
I tried to run it for several hours so the process was indeed
triggered every hour

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;

import org.quartz.DateBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class IDAScheduler {
    
    int portalId;
    String portalName;
    String portalUserName;
    String portalPassword;
    String portalServerURL;
    String portalPortNumber;
    
    //Data parametes 
    int dataId;
    String txnid;
    String dataSourceSysDSN;
    String userName;
    String password;
   
    //Schedule parameters
    int scheduleId;
    String schedule_type;
    String start_date;
    String end_date;
    String starting_time;
    String repetition;
    String status; 

    public void run() throws Exception {
        //System.setProperty(StdSchedulerFactory.PROPERTIES_FILE, "/resources/quartz.properties");

        String[] startDate = start_date.split("-");
        String[] endDate = end_date.split("-");
        String[] startingTime = starting_time.split(":");
       // dataSourceSysDSN = "abc";
        
        //Logger log = LoggerFactory.getLogger(Schedule.class);

        //log.info("------- Initializing -------------------");

        // First we must get a reference to a scheduler
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler scheduler = sf.getScheduler();
      
        Date startTime = DateBuilder.dateOf(Integer.parseInt(startingTime[0]), 
                Integer.parseInt(startingTime[1]), Integer.parseInt(startingTime[2]), 
                Integer.parseInt(startDate[2]), Integer.parseInt(startDate[1]), 
                Integer.parseInt(startDate[0]));
        
        System.out.println("Here's the start time" + startTime);
        
        
        Date endTime = DateBuilder.dateOf(Integer.parseInt(startingTime[0]), 
                Integer.parseInt(startingTime[1]), Integer.parseInt(startingTime[2]), 
                Integer.parseInt(endDate[2]), Integer.parseInt(endDate[1]), 
                Integer.parseInt(endDate[0]));

   
        System.out.println("Here's the end time" + endTime);


               
        JobDetail job = newJob(Task.class)
            .withIdentity("job" + scheduleId, "Telechoice")           
            .build();

        
      job.getJobDataMap().put(Task.DATA_SOURCE_NAME, this.dataSourceSysDSN);
        //job.getJobDataMap().put(Task.DSN_USERNAME, this.userName);
        //job.getJobDataMap().put(Task.DSN_PASSWORD, this.password);
        //job.getJobDataMap().put(Task.DMZ_USERNAME, this.portalUserName);
        //job.getJobDataMap().put(Task.DMZ_PASSWORD, this.portalPassword);
        
        SimpleTrigger trigger = null;
        
        if (schedule_type.equals("Hourly")) {
            
            trigger = (SimpleTrigger) newTrigger() 
            .withIdentity("trigger" + scheduleId, schedule_type)
            .startAt(startTime)
                .withSchedule(simpleSchedule()
                .withIntervalInHours(Integer.parseInt(repetition))
                .withRepeatCount(25)
                .withMisfireHandlingInstructionFireNow())                
            .endAt(endTime)
            .build();
            
        } else if (schedule_type.equals("Daily")) {
            
            trigger = (SimpleTrigger) newTrigger() 
            .withIdentity("trigger" + scheduleId, schedule_type)
            .startAt(startTime)
                .withSchedule(simpleSchedule()
                .withIntervalInHours(Integer.parseInt(repetition) * 24)
                .withRepeatCount(scheduleId)
                .withMisfireHandlingInstructionFireNow())                
            .endAt(endTime)
            .build();
            
        } else if (schedule_type.equals("Weekly")) {

            trigger = (SimpleTrigger) newTrigger() 
            .withIdentity("trigger" + scheduleId, schedule_type)
            .startAt(startTime)
                .withSchedule(simpleSchedule()
                .withIntervalInHours(Integer.parseInt(repetition) * 168)
                .withRepeatCount(scheduleId)
                .withMisfireHandlingInstructionFireNow())                
            .endAt(endTime)
            .build();
            
        }
       
        

        scheduler.scheduleJob(job, trigger);




        scheduler.start();

    }

    public static void main(String[] args) {
        IDAScheduler ida = new IDAScheduler();
        ida.schedule_type = "Hourly";
        ida.start_date = "2011-11-03";
        ida.end_date = "2011-11-04";
        ida.starting_time = "00:21:00";
        ida.repetition = "1";
        try {
        ida.run();
        } catch(Exception ex){
            ex.printStackTrace();
        }



    }

}

Open in new window



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

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Date;

public class Task implements Job {
    public static String DATA_SOURCE_NAME = "abc";

public void setDATA_SOURCE_NAME(String s){
         DATA_SOURCE_NAME = s;
}

 public String getDATA_SOURCE_NAME(){
         return DATA_SOURCE_NAME;
}


public void execute(JobExecutionContext context)
        throws JobExecutionException {

        // This job simply prints out its job name and the
        // date and time that it is running
        JobKey jobKey = context.getJobDetail().getKey();
           try{
    BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\temp\\test\\tt.out"));
               bw.write("Task says: " + jobKey + " executing at " + new Date());
        System.out.println("Task says: " + jobKey + " executing at " + new Date());
               bw.close();
           } catch(Exception ex){
               ex.printStackTrace();
           }
    }


}

Open in new window



Output
(the job is running as scheduled at 12:21 AM;
I also checked that it will run  every hour)



[INFO] 03 Nov 12:19:15.533 AM main [org.quartz.impl.StdSchedulerFactory]
Using default implementation for ThreadExecutor

[INFO] 03 Nov 12:19:15.548 AM main [org.quartz.core.SchedulerSignalerImpl]
Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl

[INFO] 03 Nov 12:19:15.548 AM main [org.quartz.core.QuartzScheduler]
Quartz Scheduler v.2.1.0 created.

[INFO] 03 Nov 12:19:15.548 AM main [org.quartz.simpl.RAMJobStore]
RAMJobStore initialized.

[INFO] 03 Nov 12:19:15.548 AM main [org.quartz.core.QuartzScheduler]
Scheduler meta-data: Quartz Scheduler (v2.1.0) 'MyScheduler' with instanceId 'NON_CLUSTERED'
  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 3 threads.
  Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.


[INFO] 03 Nov 12:19:15.548 AM main [org.quartz.impl.StdSchedulerFactory]
Quartz scheduler 'MyScheduler' initialized from default file in current working dir: 'quartz.properties'

[INFO] 03 Nov 12:19:15.548 AM main [org.quartz.impl.StdSchedulerFactory]
Quartz scheduler version: 2.1.0

Here's the start timeThu Nov 03 00:21:00 PDT 2011
Here's the end timeFri Nov 04 00:21:00 PDT 2011
[INFO] 03 Nov 12:19:15.579 AM main [org.quartz.core.QuartzScheduler]
Scheduler MyScheduler_$_NON_CLUSTERED started.

[DEBUG] 03 Nov 12:19:15.579 AM MyScheduler_QuartzSchedulerThread [org.quartz.core.QuartzSchedulerThread]
batch acquisition of 0 triggers

[DEBUG] 03 Nov 12:19:16.548 AM Timer-0 [org.quartz.utils.UpdateChecker]
Checking for available updated version of Quartz...

[DEBUG] 03 Nov 12:19:44.034 AM MyScheduler_QuartzSchedulerThread [org.quartz.core.QuartzSchedulerThread]
batch acquisition of 0 triggers

[DEBUG] 03 Nov 12:20:12.941 AM MyScheduler_QuartzSchedulerThread [org.quartz.core.QuartzSchedulerThread]
batch acquisition of 0 triggers

[DEBUG] 03 Nov 12:20:39.224 AM MyScheduler_QuartzSchedulerThread [org.quartz.core.QuartzSchedulerThread]
batch acquisition of 1 triggers

[DEBUG] 03 Nov 12:21:00.006 AM MyScheduler_QuartzSchedulerThread [org.quartz.simpl.PropertySettingJobFactory]
Producing instance of Job 'Telechoice.job0', class=Task

[WARN] 03 Nov 12:21:00.006 AM MyScheduler_QuartzSchedulerThread [org.quartz.simpl.PropertySettingJobFactory]
No setter on Job class Task for property 'abc'

[DEBUG] 03 Nov 12:21:00.006 AM MyScheduler_QuartzSchedulerThread [org.quartz.core.QuartzSchedulerThread]
batch acquisition of 0 triggers

[DEBUG] 03 Nov 12:21:00.006 AM MyScheduler_Worker-1 [org.quartz.core.JobRunShell]
Calling execute on job Telechoice.job0

Task says: Telechoice.job0 executing at Thu Nov 03 00:21:00 PDT 2011
[DEBUG] 03 Nov 12:21:25.945 AM MyScheduler_QuartzSchedulerThread [org.quartz.core.QuartzSchedulerThread]
batch acquisition of 0 triggers

[DEBUG] 03 Nov 12:21:52.821 AM MyScheduler_QuartzSchedulerThread [org.quartz.core.QuartzSchedulerThread]
batch acquisition of 0 triggers

Open in new window

0
 
snajalmAuthor Commented:
It ended up  that I was creating multiple instances of the scheduler and not only running the schedules awkwadly but also crashing the whole application by filling up the memory!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 11
  • 10
  • 8
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now