Mr Morgan
Mr Morgan

Reputation: 2243

Quartz scheduler and job 'firing' a second early

Can anyone advise? I have a job which runs on the hour, every hour, and which is controlled in a Java webapp by Quartz 1.8.3.

What I'm seeing though is that Quartz seems to start the job a second early sometimes. But as there's no apparent pattern to this it is difficult to correct.

My code is:

Scheduler_Job sj = Scheduler_Job_DB.get(1);       
   sj.setJobRunning(Valid.TRUE);
   Scheduler_Job_DB.update(sj);
   SQLDateTime currPollDateTime = SQLDateTime.getSQLDateTimeNow();

Where currDateTimeNow is being set to 17:59:59 when it should be 18:00:00.

The cron trigger for the Quartz job is 0 0 * * * ?

The method SQLDateTime.getSQLDateTimeNow(); simply gets the current count in milliseconds and converts it into java.sql.Date and java.sql.time elements as follows:

public static SQLDateTime getSQLDateTimeNow() {
    long milliSecs = DateTime_Utils.getTimeInMilliseconds();
    Date date = new Date(milliSecs);
    Time time = new Time(milliSecs);
    SQLDateTime sqldt = new SQLDateTime(Date.valueOf(date.toString()), Time.valueOf(time.toString()));
    return sqldt;
}

Class SQLDateTime simply has two variables as follows:

private Date sqlDate;
private Time sqlTime;

And is convenient when using dates and times stored in the database in yyyy-mm-dd HH:mm:ss format.

In 99.9% of cases this is fine but I don't understand why the job seems to fire one second early?

I should add that upgrading to Quartz 2.x is not an option.

Any ideas anyone?

My solution is to keep it simple. So if the Quartz job fires at a given hour, and if I have the job's details stored in a database table, then I can also store the current run time and date, e.g. YYYY-MM-DD 18:00:00.

So the job fires, it reads the details including the date and time from the database, and makes all the updates for 18:00:00.

Then at the end of the job, the current run time and date get incremented by an hour and are written back to the database for use as the next run date and time. So 18:00:00 becomes 19:00:00 and the date stays the same unless the job is running at 23:00:00.

So everything is in synch and there's no playing with milliseconds.

It sounds good in theory anyway...

Upvotes: 2

Views: 1350

Answers (1)

Angelo Fuchs
Angelo Fuchs

Reputation: 9941

It could be that the different clocks are marginally offset, so when the quartz scheduler starts on 18:00:00 005 it could be that the database still thinks its 17:59:59 980.

If its really an issue to you, you might want to sleep the thread some hundred millis so its always correct.

Upvotes: 1

Related Questions