How can I schedule time to stop and kill a single job
from the begining of execution task ?
For example determine that if after an hour the task is still working, it will stop and remove. (I don't mean to Repeated task)
I use with org.quartz.Scheduler and org.quartz.JobDetail in java
many thanks
You might want to look into the org.quartz.InterruptableJob interface (which extends Job) and the interrupt() method on the scheduler.
If you want to actually call Thread.interrupt() on the threads in the worker thread pool you'd likely need your implementation of org.quartz.spi.ThreadPool.
I think it would probably be easier for you if you coded this functionality within the job itself. I say this for a few reasons:
Its very easy to track how long the job has been running from within the job
If the job needs to stop, its easy to stop gracefully and set aside the work it was doing
Your job may be able to tell progress on the works its doing, and if its close to being done let it go beyond the kill-time + 10% or something
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*/}
}
Couple more options are here
Related
I'm using a ScheduledExecutorService to run a particular job (implemented as an ordinary Runnable) periodically once in a minute (using method scheduleAtFixedDelay()).
Occasionally, however, I would like it to wake up immediately, invoke the Runnable and then return to its ordinary policy (i.e. wait 1 minute again).
Is there a simple way to achieve this?
I've checked the API of the ScheduledExecutorService and its superclasses, but so far didn't find anything suitable.
Of course I could resort to some other method, like pass the same Runnable to a separate Thread created for the exceptional purpose, but using a method of the ScheduledExecutorService would be more elegant.
Just remember the ScheduledFuture from your call to schedule.
If you then want to run it ahead of time, call future.cancel(), submit the Task again for immediate execution and then schedule it again.
I have read this page over several times, and am just not seeing some of the inherent differences between GWT's Timer and Scheduler classes. I'm looking for the use cases and applicability of each of the following:
Timer, Timer::schedule and Timer::scheduleRepeating
Scheduler::scheduleDeferred
Scheduler::scheduleIncremental
IncrementalCommand
DeferredCommand
These all appear to be doing the same thing, more or less, and it feels like you can accomplish the same objectives with all of them. Is this just GWT's way a providing multiple ways of doing the same thing? If not, please help me understand when and where each is appropriately used.
Use Scheduler when you need a browser to complete whatever it is currently doing before you tell it to do something else. For example:
myDialogBox.show();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
#Override
public void execute() {
myTextBox.setFocus();
}
});
In this example, focus will not be set until the browser completes rendering of the dialog, so you tell the program to wait until the browser is ready.
Use Timer if you want some action to happen after a specified period of time. For example:
notificationPanel.show();
Timer timer = new Timer() {
#Override
public void run() {
notificationPanel.hide();
}
};
timer.schedule(10000);
This code will show notificationPanel, and then it will hide it after 10 seconds.
As the JavaDoc says, DeferredCommand is deprecated in favor of Scheduler.
The problem with DeferredCommand and IncrementalCommand is that they have a static state (which makes it hard to use reliably in tests). Moreover, their (static) methods make JSNI calls which forces you to use a GWTTestCase to test your code (static methods aren't –easily– mockable). Static methods also make it impossible to wrap them (to, e.g. add some logging or whatever).
On the other hand, you work with an instance of a Scheduler (if you want testable code, you'll use dependency-injection to get a instance of a scheduler and will never call Scheduler.get() except in your DI "factory"). In a test, you can then use a StubScheduler for instance.
Then there's Timer, which is similar to the others but the scheduled task can be cancelled. Note that Timer makes use of JSNI too, just like DeferredCommand; any kind of code that uses a Timer will need a GWTTestCase to be unit-tested.
I have a static, periodic, java Timer/TimerTask that I would like to shutdown when the app does. I don't want the app hanging because some thread is still running (like what happens in debug mode in eclipse, some environments may kill the thing anyway). The reason I have it static is I plan to have some (very simple, probably just a counter) shared memory in all of the containing class's instances with the Timer so I feel class scope is appropriate.
My question is how best to do the shutdown of the Timer? Is this an appropriate time to use finalize? This timer seems benign enough that having a non-deterministic call to finalize may work? Would probably need to do some kind of instance counting to verify that there are no longer any instances of the class out there? Suggestions on ways to manage the shutdown of the static Timer are welcome.
pseudo code:
class foo {
private static Timer someTimer = null;
public foo() {
if(someTimer == null) {
someTimer = new Timer(new TimerTask(...));
}
}
//how should I shut this thing down?
protected void finalize() throws Throwable {
}
//or is better to have shutdown() called explicitly?
}
It all depends on what your app actually does, but in general there will be some kind of event to signal that the app is being shutdown. For example if it's a GUI app, then maybe this will be the "user clicked on the Quit button" event. Or it's a webapp based on the servlet API, it will be an event fired by a ServletContextListener.
You should add a listener for this event, which calls some kind of shutdown method on your foo object. Inside this shutdown method the foo should take care of cleaning up its resources, including stopping the timer.
As a last resort, you might want to investigate JVM shutdown hooks
currently i am developing a set of simple games for Java (with JavaFX2 as GUI). Just now i ran into the need of "pausable timers". Does anybody know a library for game timing that enables me to pause timers without implementing it myself? For implementing countdowns and fixed rate things.
I need to:
- schedule TimerTasks at a specific rate (thats already in the JDK)
- schedule TimerTasks with a fixed delay
- pause the timer
- resume the timers so that everything starts of where i paused it.
It would be really cool if somebody knew something like that.
Thanks.
I'm pretty certain there's nothing in the JDK that does this, and I don't know of any libraries to do it.
However, I think instead of trying to pause and resume some sort of timer, you should simply wrap anything that relies on executing periodically in a condition so that it only executes when not paused. If the rate at which tasks are scheduled is sufficiently fast, the difference should not be noticeable for the user. For example:
public abstract class PausableTask extends TimerTask {
private final AtomicBoolean isPaused;
public PausableTask(AtomicBoolean flag) {
isPaused = flag;
}
#Override public final void run() {
if (!isPaused.get()) go();
}
public abstract void go();
}
Then you could have one global paused flag, and any time you are using TimerTasks, use this class instead, passing the global flag. You could even make the flag a public static variable of the PausableTask class.
Maybe this approach isn't even applicable to your game and you have some reason to need more accurate pausing, but if not, hopefully this helps!
You may want to take a a look at Quartz Standby method -
http://www.quartz-scheduler.org/docs/api/1.8.1/org/quartz/Scheduler.html#standby()
From the API -
Temporarily halts the Scheduler's firing of Triggers.
When start() is called (to bring the scheduler out of stand-by mode), trigger misfire instructions will NOT be applied during the execution of the start() method - any misfires will be detected immediately afterward (by the JobStore's normal process).
The scheduler is not destroyed, and can be re-started at any time.
Quartz is a very good framework which you can plugin to your application. It is also highly customizable so you can utilize it.
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?
Quartz 1
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*/}
}
Quartz 2
In version 2.0 of Quartz, StatefulJob is deprecated. It is now recommended to use annotations instead, e.g.
#DisallowConcurrentExecution
public class YourJob implements org.quartz.Job {
void execute(JobExecutionContext context) {/*implementation omitted*/}
}
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.
Just in case anyone references this question, StatefulJob has been deprecated. They now suggest you use annotations instead...
#PersistJobDataAfterExecution
#DisallowConcurrentExecution
public class TestJob implements Job {
This will explain what those annotations mean...
The annotations cause behavior just as
their names describe - multiple
instances of the job will not be
allowed to run concurrently (consider
a case where a job has code in its
execute() method that takes 34 seconds
to run, but it is scheduled with a
trigger that repeats every 30
seconds), and will have its JobDataMap
contents re-persisted in the
scheduler's JobStore after each
execution. For the purposes of this
example, only
#PersistJobDataAfterExecution
annotation is truly relevant, but it's
always wise to use the
#DisallowConcurrentExecution
annotation with it, to prevent
race-conditions on saved data.
if you use spring quartz, i think you have to configure like this
<bean id="batchConsumerJob"class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="myScheduler" />
<property name="targetMethod" value="execute" />
<property name="concurrent" value="false" />
</bean>
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 ?
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.
You can use a semaphore. When the semaphore is taken, abandon the 2nd job and wait until the next fire time.