Start Multiple java TimerTasks at the same time - java

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.

Related

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,

How can I schedule Java tasks at guaranteed fixed rate, independent of task run time?

java.util.Timer's scheduleAtFixedRate is an obvious alternative if one wants to schedule tasks at a certain interval. However, if your interval is 10 s. and the tasks take more than 10 s. this function will busy-execute anything pending according to the documentation (quote: two or more executions will occur in rapid succession to "catch up."). This is of course a reasonable way to implement it, but it's not necessarily what you want.
Does anyone know about standard functionality in the Java API for scheduling task n+1 <interval> milliseconds after task n, independent of how long time task n took?
I've implemented this functionality myself twice now (two different projects) because it's simply the most correct way to implement it in the cases I've stumbled upon.
You might say this is trivial (and it is) but I hadn't mentioned it if it wasn't a recurring thing.
My main point here is that if the "catching up" strategy is deemed "correct", then my approach here would be equally correct in quite a few cases and I think scheduleAtFixedRate should include an option for it. This isn't a problem for me, I just wanted to see if anyone knew if this was implemented already in the Java API so I don't have to code it now and then.
This would be accomplished with the schedule() methods (assuming java.util.Timer is being used). It provides fixed delay as opposed to fixed rate.
After some (re)searching, I believe the scheduleWithFixedDelay method of ScheduledExecutorService implements exactly this.
I think this does exactly what you want. Java.util.timer -> schedule(TimerTask task, long delay, long period). This executes with "fixed delay".
According to the documentation: In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well.

check if the timer has any pending tasks?

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.

Java Timer and scheduleAtFixedRate + System Suspend

I am working on a Java program and using Timer objects to run tasks every few minutes or hours. This works fine in normal operations, but I am running into a problem with "Sleep mode" on Mac (maybe on other OSes, but I haven't tried yet).
Consider this code sample:
//Setup the timer to fire the ping worker (every 3 minutes)
_PingTimer.scheduleAtFixedRate(new TimerTask(){
public void run(){
Program.PingThread = new PingWorker(Settings.Username, Settings.UserHash, true, true);
Program.PingThread.CheckOpenPort = true;
Program.SwingExecutor.execute(Program.PingThread);
}
}, 0, 180000);
In normal operation this would fire every 3 minutes with enough accuracy (I'm not concerned about the exact second or anything). The problem with this is after sleeping the computer for a few hours or so it seems to just BLAST the system with backlogged timer requests.
It seems to be running all of the missed timer hits during sleep at once trying to make up for lost time.
Is there a way i can prevent this? I tried using synchronized and some other thread techniques, but this only ensures that they aren't all running at the same time. They still continue to run one after another until the backlog is passed.
Thanks for any help you can provide!
Have you looked at the API? It clearly states the following:
In fixed-rate execution, each
execution is scheduled relative to the
scheduled execution time of the
initial execution. If an execution is
delayed for any reason (such as
garbage collection or other background
activity), two or more executions will
occur in rapid succession to "catch
up." In the long run, the frequency of
execution will be exactly the
reciprocal of the specified period
(assuming the system clock underlying
Object.wait(long) is accurate).
This is one reason why you should consider using a ScheduledExecutorService. This link may also prove useful.
Use schedule instead of scheduleAtFixedRate.

Java timer class, to fire at a fixed time everyday

I want to write a simple timer class that fires , and makes a method call at a fixed time of every day, while the application is running.
I dont want to use Quartz as I think its a overkill for this simple problem, what are the different approaches I can try for ?
Thanks in Advance
Why not use java.util.Timer and java.util.TimerTask?
The util.concurrent's ScheduledExecutorService allows you to pretty easily schedule tasks to run on a fixed delay. The signature of the schedule method is as follows:
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
You could find the difference between the current time and the time in which you wish to have it first run. Set the difference as the value for initialDelay. Set the period to 1 and the TimeUnit unit to TimeUnit.DAYS. That will cause it to run every day at that time.

Categories