Can I use the Java timer class for timed data collection? - java

I am writing a program that collects a series of angle inputs during a trial and saves these to a file with their corresponding timestamps.
For example:
1 sec 260 degrees
2 sec 45 degrees
3 sec 60 degrees
etc.
When running a trial, the user should be able to pause and restart or fully abort the trial if need be.
I am running into trouble with the pause functionality. I have been using the Java Timer and TimerTask classes to time the input, as it provides much of the functionality I am looking for (start a task after a delay, only record data at certain intervals, etc.).
Within my timerTask, I have been storing the collected angles and times in parallel arrays, and then at the end of the trial, writing these arrays to a file.
However, when I "pause" my timerTask via the timer.cancel() function and restart it, the old data arrays are thrown away. I have tried to sidestep this issue by saving the "paused" array and then merging it with the "restarted" array at the end of the restarted trial, but this doesn't account for the fact that a trial could be paused numerous times.
Are the timer/timerTask classes the wrong classes to be using for this job? Is there a better way to collect time-based data in Java? Or am I just overlooking a solution?

As the API specifies Timer.cancel()
Terminates this timer, discarding any currently scheduled tasks.
The simplest way to achieve the functionality you desire would probably be to store a 'paused' boolean and toggle it when the user pauses/unpauses. Then check the state of the boolean from within your task and simply return; if the trial is paused. The Timer will still fire every second, but nothing will happen as long as the trial is paused.

Related

Can I avoid multiple timers?

In my app I want to do some stuff corresponding to each specific user response. User responses occur continuously with minimum 130 milliseconds interval. I want to run some code after 3 seconds, 10 seconds and after 30 seconds for each specific response. I know I can use multiple timers or handlers for delay. But how to do that with minimum load on processor and memory.
One solution could be to keep a sorted queue of "upcoming" events.
Each time your single timer wakes you up, you simply check if the time has come to process the top element in that queue. If so, do what needs to be done for that event and remove it from the queue.

Time limit on input thread

I am creating an IRC bot using Pircbot that can respond to certain requests (e.g. "!time" provides local time). One of the functions I am building is a giveaway system that randomly selects a user from the currently online users and gives them a prize.
I would like to enhance the system by forcing the winner to type "!accept" within 30 minutes of winning in order to claim the prize. However I would like the bot to still function, meaning I can't freeze the entire thread for 30 minutes waiting for a message.
A few ways I am thinking of doing it feel a bit too hacky to me.
I can store the winner's name in a variable or a .properties file, and constantly be on the lookout for the "!accept" command. If an "!accept" was sent by the winner (the name in the variable) and the message sent time was within 30 minutes, confirm winner. The downside to this is if the bot restarts or is taken offline temporarily in this 30 minute period, it could cause a lot of continuity problems, especially with a .properties file.
Create a runnable thread, sleep for 30 minutes and then check all new messages for the !accept command. This sounds extra hacky with hacky sauce on top.
Dance my problems away.
Mark the time you choose the winner, maybe even have another Thread or Timer event which gets triggered after 30 minutes to reset it.
If the input is "!accept" and is from the correct user AND the difference between the "marked" time and now is less then 30 minutes, happy user

Constantly nulling out and re-creating Timer, TimerTask in Java

I know using Timer and TimerTask is no longer the current accepted practice (some have suggested using threads, others suggest using ScheduledExecutorService or its variants), so this question is not so much about good programming practice, but about the possibility of actual errors or exception.
Essentially, what I have is a servlet that keeps a running counter (which is a static Calendar object) that gets incremented every second. When a specified deadline is met (when we reach 10 minutes by default), I make a call from my application to a NIST time server to get the current time, which I then use to re-set my counter.
The same TimerTask-defined method that increments the counter (every second) is also the one that must be paused and re-scheduled every time I make a call to a NIST server (every ten minutes). I have been unsuccessful in pausing/cancelling the existing Timer/TimerTask objects before the NIST server call and re-scheduling the TimerTask after the call.
The exceptions that occur from this are described here:
How do I use a timer in Java when required to set and cancel multiple times?
Suffice it to say, neither TimerTask nor Timer can be scheduled more than once, even by using purge() or cancel(), which appear to be only good for setting those objects as eligible for Java garbage collection.
Using wait() and notify() resulted in synchronization exceptions that I, unfortunately, did not have the time to figure out, so my initial experiment with threading was a failure.
What I ended up doing is this:
secondTickerTask.cancel();
secondTicker.purge();
secondTicker.cancel();
secondTickerTask = null;
secondTicker = null;
Date newCurrentTime = getNistTimeFromFirstWorkingServer();
// Save new date to current time, reset second counter.
setCurrentTimeAndDeadline(newCurrentTime);
startSecondIncrementTimer(newCurrentTime);
secondTicker = new Timer();
secondTickerTask = new TimerTask(){
public void run(){
incrementCurrentTimeAndTestDeadline();
}
I ran this code over-night a few times, at 10-minute and 1-minute intervals between NIST server calls, and it worked smoothly.
So, after that long lead-up (thank you for your patience), this is what my question is: Being forced, for the moment, to use the code that I have, is there any damage that could result in the long run? If I keep making new TimerTask and Timer objects while nulling out the old ones over, let's say, a period of a month, or six months, will I force the Server to run out of memory? Is Java's garbage collection robust enough to handle this sort of use? Can any other scary thing happen?
Thank you very much for your time,
- Eli
Java will handle the creation and abandonment of the timer tasks just fine. You need to ensure that you drop all references to the timers when you are done with them, which it appears you are doing, and then when the GC runs it will clean up any garbage the Timers introduced.
You are safe.
You should note that, over long periods of time, some Java processes tend to keep allocating memory until they hit their -Xmx limit. This does not mean that there is a problem (because that space will be reused by the GC), but it also means that, if you want a long-running Java process to have a relatively small footprint that you should not specify an -Xmx much larger than what you actually need.

java, calling a method after a modifiable delay

I'd like to ask you about the best solution/idea how to solve a following situation.
I'm developing an Android app which on one of screens has a set of buttons. After clicking on any of them a kind of config is posted to the server over http.
To prevent multiple clicks one by one which could result in concurrency problems I decided that after each click on a particular button there'll be a waiting interval of 30 seconds before a config is sent to the server. If another click on the same button happens before this 30 seconds are exceeded, then the execution of method is delayed for another 30 seconds - as long as no new click is performed, then the config will be sent.
I need an idea of an algorithm which would implement the mechanism above. What I know is that I don't want to start a separate thread for each click (too heavy for my app). A potential idea is to make a queue of events and send them in a loop but idea of a running endless loop in a thread (or Handler) also isn't my favourite.
Maybe there's a kind of mechanism in Android or J2SE in general, that allows to schedule an execution of method to a given time in the future but still be able to postopone execution for some additional time before 30sec rolled out.
thanks in advance!

Using multiple timers in a Java application with animation

I'm writing a Java Application that will side scroll sheet music across the screen and then when it crosses a middle line, it will play the note(s).
It will have a variable speed based on the beats per minute.
Every quarter of a beat I need to have a "tick" function that will get the next note (if any) and start its animation. To calculate this tick I have a function 60000ms/bpm/4. This will be separate from the animation timer, because the repaint should probably be called at some constant rate.
So I'm thinking I need Util Timer for the "ticks" and a swing timer for the JPanel and drawing in the paintComponent() method.
My question is: What would be the best practice for accomplishing this? I've done a fair amount of Java programming, but no Swing or animations so I would like to learn the best way to do this.
Thanks
Nate
There is no reason to use Timer or TimerTask to solve this problem.
In this case, you have a series of notes, and when you start playing, you can calculate ahead of time, the exact time that each and every note should play. I am assuming that you already have some sort of loop that is updating the display at a steady rate. (e.g. 30 refreshes per second, or something like that). Given such a loop, all you need is an event oriented class that can tell you whether it is time to play a note.
long noteTime[] = new long[numberOfNotes];
long startTime = System.currentTimeMillis();
Declare the above array. Then walk through all the notes in the song, and calculate the time that each note is expected to play. Say you have qurter notes, the first note will play at startTime, the second one beat after startTime, the third two beats after start time, etc. This is where you calculate the time for a beat and use it. Just calculate the actual time values for each note to play.
Then, in the middle of your event loop that is refreshing the display, include the following code:
int nextNote = 0;
while (event_loop_condition) {
.
.
.
if (System.currentTimeMillis()>noteTime[nextNote]) {
playNote(nextNote++);
}
.
.
.
}
The point is that you already have an event loop, all you need to know is whether it it time yet to play the note, and this will do that for you.
On the other hand, if you are not handling the refresh, and you really do want to do this on a thread, the follow method can be called on a thread, and it will play all the notes at the correct times:
playAllNotes() {
for (int i=0; i<numberOfNotes; i++) {
Thread.sleep(noteTime[i]-System.currentTimeMillis());
playNote(i);
}
}
The sleep statement will delay until the time that the note should be played, and will play it at that time. Then it will sleep until the time for the next note to be played.
The important thing to notice about both methods, is that any delay in playing a note is NOT compounded for the next note. Say some system utility kicks in and delays one note by 50ms. The next note will not be delayed by this, because you calculated all the times for all the notes to be played up front. Given that threads are competing for CPU time, you will have thread/process contention, and there will be small variances in the time that notes are played, but they will never compound!
A lot of programmers inappropriately use timers (See discussion of Timers) on my website if you want to know more.

Categories

Resources