views:

1412

answers:

5

I have a Java program that executes from Spring Qquartz every 20 seconds. Sometimes it takes just few seconds to execute, but as data gets bigger I'm sure it run for 20 seconds or more.

How can I prevent Quartz from firing/triggering the job while one instance is still being executed? Firing 2 jobs performing same operations on a database would not be so good. Is there a way I can do some kind of synchronization?

Thank you

A: 

put them in a queue

Even if the time exceeds 20 second current job should be finished & then the next should be fetched from the queue.

Or you can also increase time to some reasonable amount.

Asad Khan
+4  A: 

If all you need to do is fire every 20 seconds, Quartz is serious overkill. The java.util.concurrent.ScheduledExecutorService should be perfectly sufficient for that job.

The ScheduledExecutorService also provides two semantics for scheduling. "fixed rate" will attempt to run your job every 20 seconds regardless of overlap, whereas "fixed delay" will attempt to leave 20 seconds between the end of the first job and the start of the next. If you want to avoid overlap, then fixed-delay is safest.

skaffman
Simple is so elegant...
Zoidberg
A: 

I'm not sure you want synchronisation, since the second task will block until the first finishes, and you'll end up with a backlog. You could put the jobs in a queue, but from your description it sounds like the queue may grow indefinitely.

I would investigate ReadWriteLocks, and let your task set a lock whilst it is running. Future tasks can inspect this lock, and exit immediately if an old task is still running. I've found from experience that that's the most reliable way to approach this.

Perhaps generate a warning as well so you know you're encountering problems and increase the time interval accordingly ?

Brian Agnew
Downvoted why ?
Brian Agnew
A: 

you can use a semaphore. when the semaphore is taken, abondon the 2nd job en wait till the next fire time

Salandur
+9  A: 

If you change your class to implement StatefulJob instead of Job, Quartz will take care of this for you. From the StatefulJob javadoc:

stateful jobs are not allowed to execute concurrently, which means new triggers that occur before the completion of the execute(xx) method will be delayed.

StatefulJob extends Job and does not add any new methods, so all you need to do to get the behaviour you want is change this:

public class YourJob implements org.quartz.Job {
    void execute(JobExecutionContext context) {/*implementation omitted*/}
}

To this:

public class YourJob implements org.quartz.StatefulJob {
    void execute(JobExecutionContext context) {/*implementation omitted*/}
}
Don
That is the correct answer to this question. Thanks.
cherouvim