check if the timer has any pending tasks? - java

I use the Java's Timer to schedule a task to run after some interval of time.
myTimer.schedule(myTask, delayTime);
At any point in time, is it possible to check if there is any task scheduled to be run (but has not run yet)? If so, how would I do that?
If not, what is the alternative(s) to Timer do I have?

You can (and should) use ScheduledExecutorService instead of Timer.
It handles thread crashes in a robust manner and has more flexible API

You can just add a boolean field to myTask's class, which will be set true at first execute.
Keep it simple.

Related

How to let a ScheduledExecutorService run a Runnable ahead of the scheduled time?

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.

How to remove/postDelayed runnables in Java?

Upon an event, I'd like to run a task/runnable but delay it's execution in 2 seconds.
During these 2 seconds, if the same event occurs, I'd like to remove the previous task and re-post it to run - again delayed by 2 seconds.
An example scenario would be background compilation. When a file is saved, I'm waiting 2 seconds and start compiling the class and other, depending classes. I don't want to do it all the time - especially if there are editors that save files automatically, like IntelliJ IDEA.
So, how can I remove/postDelayed runnables in Java, like Android's Handler (remove / postDelayed)?
you can use the Executors.newScheduledThreadPool in order to schedule the task,
and you can follow this post's answer :
BlockingQueue<Runnable> queue = threadPool.getQueue();
in order to get the queued runnables.
To delay any task and "restart" the delay, you can use Swing timer and if it is running, use its method restart.
I suppose you could use the ScheduledExecutor to accomplish this, by adding a mechanism to replace queued tasks with re-queued ones. You could look into the source code of ScheduledThreadPoolExecutor to give an idea, perhaps overriding the implementation of ScheduledFuture<?> schedule( Runnable command, long delay, TimeUnit unit ) and figuring out to avoid the scheduling, only running the tasks once.
Cheers,

Start Multiple java TimerTasks at the same time

Is it possible to schedule multiple TimerTasks such that they all begin at the same time and if so how would I do it? In particular I would like to initiate these tasks at the same exact time so that the relative time difference between each task is as specified (I want to be as accurate as possible).
toneIntervalClock.scheduleAtFixedRate(tonePlayerTask, 250, 5000);
startRecordingClock.scheduleAtFixedRate(startRecordingTask,0,5000);
stopRecordingClock.scheduleAtFixedRate(stopRecordingTask, 1000, 5000);
Also would it be better practice to use the same Util Timer to schedule each task?
Thanks
The system will try to make scheduleAtFixedRate tasks fire with low jitter, but you don't ever get any guarantees with concurrency.
Your approach of trying to initialize all of the tasks and then run them is a decent one. The only suggestion I would make is to use Timer#scheduleAtFixedRate(TimerTask task, Date firstTime, long period), since then you don't have any jitter in between your schedule calls and can start them all from a fixed time reference.

How to cancel Spring timer execution

I need to cancel Spring timer execution or at least change the execution frequency based on some conditions. Was using both org.springframework.scheduling.quartz.SimpleTriggerBean and org.springframework.scheduling.timer.ScheduledTimerTask. Cannot find the way how to do it.
NOTE: This is for Spring 3.0+
Read Spring documentation on scheduling tasks
Use a TaskScheduler service, such as a TimerManagerTaskScheduler or ThreadPoolTaskScheduler.
Schedule your task by calling some TaskScheduler.schedule*() method and store the returning ScheduledFuture.
When you want to cancel execution, invoke ScheduledFuture.cancel(). That will stop further invocations of your task. At this time, you can reschedule if you want by calling TaskScheduler.schedule*() for your task with different parameters.
This is by far not the best solution but if you can't come up with anything else you could always use a boolean that would be checked each time the event is fired and if the boolean is false the run method of the timertask should immediately terminate.
The solution is to assign an id to the org.springframework.scheduling.timer.TimerFactoryBean and then retrieve this bean from the application, cast it to Timer and call cancel method on that object.

Scheduling multiple tasks using timers

How can I schedule multiple tasks using java.util.Timer. I want to read multiple files using timers. I think I have to give each file a different TimerTask so that one file gets one instance of TimerTask and other file gets another, but I don't know how to do it. Please help. Thanks in advance. Here is what I'm doing:
Timer timer = new Timer();
// repeat the check every second
timer.schedule(fileWatcherTask, new Date(), 1000);
As javadoc of Timer class indicates your tasks should take very few time. In this case you can forget about time clash. If your tasks take more then 0.1 seconds run them in separate thread. I mean use Timer as a trigger that just makes task to start in separate thread.
you can also use quartz scheduler for that refer http://www.mkyong.com/java/quartz-scheduler-example/
if you want to use timer class see the example in following image
refer link for more details

Categories