What are the method parameters of Java's Timer#schedule - java

I'm currently trying to use a Timer to execute an action at set intervals.
I've taken a snippet from Stack Overflow, however it did not have an explanation, and I'm struggling to figure out what it's parameters mean.
Could someone please explain to me the parameters for the method?
It's namely the last 2 parameters, 5000, 5000 which I don't understand.
TimerTask damageInterval = new TimerTask() {
public void run() {
playerInfoPanel.health -= monsterDamage - playerInfoPanel.defenceLevel;
}
};
inflictDamage.schedule(damageInterval, 5000, 5000);

JavaDocs are your friend
public void schedule(TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-delay execution,
beginning after the specified delay. Subsequent executions take place
at approximately regular intervals separated by the specified period.
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. In the long
run, the frequency of execution will generally be slightly lower than
the reciprocal of the specified period (assuming the system clock
underlying Object.wait(long) is accurate).
Fixed-delay execution is appropriate for recurring activities that
require "smoothness." In other words, it is appropriate for activities
where it is more important to keep the frequency accurate in the short
run than in the long run. This includes most animation tasks, such as
blinking a cursor at regular intervals. It also includes tasks wherein
regular activity is performed in response to human input, such as
automatically repeating a character as long as a key is held down.
Parameters: task - task to be scheduled. delay - delay in milliseconds before task is to be executed. period - time in
milliseconds between successive task executions.

Related

About java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate : how frequently it executes task?

I was looking at javadoc of --> java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate
I have re-produced below the javadoc:
ScheduledFuture<?> java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor. If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
Parameters:
command the task to execute
initialDelay the time to delay first execution
period the period between successive executions
unit the time unit of the initialDelay and period parameters
Returns:
a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
I understood that first time it would be enabled after initialDelay and then repeated after period. However, looking at highlighted section above, it seems frequency is increasing in-between the successive executions.
Is this the correct behaviour? If so, then the delay would get increased from previous executions?
Can anyone help clarify?

How to schedule a timed event which is unaffected by computer suspend

I want to schedule an event to happen at a particular time, regardless of whether the computer suspends in the meanwhile. If computer is suspended when the event should have occurred, I want it to be scheduled immediately on resume.
I tried two ways: a thread with a sleep(), and a Swing Timer. Both these methods rely on a timed delay, and both suffer the same problem in that the delay countdown is suspended when the computer suspends, and continues only when the computer resumes, so the event occurs at (original delay + time suspended).
I then guessed that what I should be doing is to use a (util) Timer with a target Date, as this specifies a point in time, like so:
Date targetDate = new Date(System.currentTimeMillis() + (60 * 1000)); // in 1 min
Timer eventTimer = new Timer();
eventTimer.schedule(eventThread, targetDate);
Unfortunately this suffers in exactly the same way.
I did also look at the ScheduledExecutorService (although overkill for this application I thought) but it explicitly uses delays, so I assumed it would suffer the same problem.
Is what I want to do possible?
the delay countdown is suspended
No, this is not really what happens. Otherwise it would mean the system time would be wrong on resume!
Is what I want to do possible?
Here is a solution:
have one task handle all the scheduling, which runs, say, every second;
in a task to be executed, record the time, make the class of your task Comparable against the expected execution time;
put all these tasks in a PriorityQueue (or even a PriorityBlockingQueue);
when the scheduling task wakes up, peek the tasks; if the expected execution time is less than, or equal, to the current time, dequeue it and execute it; repeat until the peeked task has an expected execution time greater than the current time.
This will not make for "immediate execution upon resume", but close to.
Things are even weirder. I have a program that refreshes data on an hourly basis, using java.util.Timer and a suitable TimerTask. With openSuse up to version 13.1 that program worked as required - when due to a suspend the real time exceeded the cycle, the task was called "immediately" after the resume.
Running the same program with the same jvm (1.8.0_40-b10) and the same Linux kernel (3.14.24), but with openSuse 13.2, the task is not called on resume but only after the period has expired in wake mode.
I have solved this problem by calling the task via a function key if the current time exceeds the scheduled time and resynchronizing the task if necessary. That's a nuisance but acceptable because the resume is anyway done via a key stroke.

how to run timertask once in a day only one week?

for(Date timerDate1=startDate; timerDate1<=cal3.add(cal3.DATE,7);startDate=cal3.add(cal3.DATE,1))
{
long period=60*60*1000;
Timer timer = new Timer();
timer.schedule(new MyTask(),timerDate,period);
cal3.add(cal3.DATE,1);
}
Use timer.scheduleAtFixedRate
void java.util.Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)
scheduleAtFixedRate
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period. 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).
Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.
Parameters: task - task to be scheduled. delay - delay in milliseconds before task is to be executed. period - time in milliseconds between successive task executions. Throws: IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative. IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
Instead of a for-loop, use a single Timer, and pass your task to one of the scheduleAtFixedRate methods of Timer, with a period of TimeUnit.DAYS.toMillis(1).
Your task class should be constructed with a starting Date and the class should store that date in a field. In the class's run method, use a Calendar to check whether the current time, minus 7 days, is later than the task's start date, and if it is, call cancel() and return immedately.

Android Timer schedule vs scheduleAtFixedRate

I'm writing an Android application that records audio every 10 minutes. I am using a Timer to do that. But what is the difference between schedule and scheduleAtFixedRate? Is there any performance benefit in using one over the other?
The difference is best explained by this non-Android documentation:
Fixed-rate timers (scheduleAtFixedRate()) are based on the starting time (so each iteration will execute at startTime + iterationNumber * delayTime).
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."
Fixed-delay timers (schedule()) are based on the previous execution (so each iteration will execute at lastExecutionTime + delayTime).
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.
Aside from this, there is no difference. You will not find a significance performance difference, either.
If you are using this in a case where you want to stay synchronized with something else, you'll want to use scheduleAtFixedRate(). The delay from schedule() can drift and introduce error.
A simple schedule() method will execute at once while scheduleAtFixedRate() method takes and extra parameter which is for repetition of the task again & again on specific time interval.
by looking at syntax :
Timer timer = new Timer();
timer.schedule( new performClass(), 30000 );
This is going to perform once after the 30 Second Time Period Interval is over. A kind of timeoput-action.
Timer timer = new Timer();
//timer.schedule(task, delay, period)
//timer.schedule( new performClass(), 1000, 30000 );
// or you can write in another way
//timer.scheduleAtFixedRate(task, delay, period);
timer.scheduleAtFixedRate( new performClass(), 1000, 30000 );
This is going to start after 1 second and will repeat on every 30 seconds time interval.
According to java.util.Timer.TimerImpl.TimerHeap code
// this is a repeating task,
if (task.fixedRate) {
// task is scheduled at fixed rate
task.when = task.when + task.period;
} else {
// task is scheduled at fixed delay
task.when = System.currentTimeMillis() + task.period;
}
--
java.util.Timer.schedule(TimerTask task, long delay, long period)
will set task.fixedRate = false;
java.util.Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)
will set task.fixedRate = true;
btw Timer doesn't work when screen is off.
You should use AlarmManager.
There is sample:http://developer.android.com/training/scheduling/alarms.html
In case of schedule it only executes once when the appropriate times came. On the other hand scheduleAtFixedRate has an extra parameter period which contains amount of time in milliseconds between subsequent executions.
More info can be find here
http://developer.android.com/reference/java/util/Timer.html#schedule(java.util.TimerTask, long)

What happens if a TimerTask takes longer to execute than the specified interval?

When using
Timer.schedule(TimerTask task, long delay, long period)
(i.e. with fixed-delay execution), what happens if the specified TimerTask's run() method takes longer than period to complete? Is it possible that two concurrent TimerTask threads will be running because of this?
And if so, is there a way to avoid it?
Timer's documentation says the following:
Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.
That is, concurrent TimerTask threads will not be running. The tasks will accumulate into a queue. This may or may not be appropriate (more likely, not).
Timer and TimerTask don't handle this sort of situation well. If you want to handle it better, then don't use those classes.
java.util.concurrent.ScheduledExecutorService provides two scheduling methods, scheduleAtFixedRate and scheduledWithFixedDelay, which govern what happens when tasks "bunch up".
scheduleAtFixedRate:
Creates and executes a periodic action
that becomes enabled first after the
given initial delay, and subsequently
with the given period; that is
executions will commence after
initialDelay then initialDelay+period,
then initialDelay + 2 * period, and so
on. If any execution of the task
encounters an exception, subsequent
executions are suppressed. Otherwise,
the task will only terminate via
cancellation or termination of the
executor. If any execution of this
task takes longer than its period,
then subsequent executions may start
late, but will not concurrently
execute.
scheduleWithFixedDelay:
Creates and executes a periodic action
that becomes enabled first after the
given initial delay, and subsequently
with the given delay between the
termination of one execution and the
commencement of the next. If any
execution of the task encounters an
exception, subsequent executions are
suppressed. Otherwise, the task will
only terminate via cancellation or
termination of the executor.
You can create ScheduledExecutorService instances using the Executors factory class.

Categories

Resources