While scheduling tasks using java.util.TimerTask how i can make sure that run method will execute only after current execution is completed, otherwise tasks queue size will keep growing and eventually task will be executing always. i am beginner and looking help
Use ExecutorService#scheduleWithFixedDelay(). This will start the 'delay' when the current task finishes (as opposed to scheduleAtFixedRate())
Use a java.util.Timer with the TimerTask. One of these timer's two methods can be used:
schedule(TimerTask task, long delay, long period)
scheduleAtFixedRate(TimerTask task, long delay, long period)
Where:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Also, refer this article: What is the difference between schedule and scheduleAtFixedRate?
Related
I created a Timer object scheduled to run every 1 second and the run method takes 20 seconds to complete. The
Timer.schedule method works as expected: it starts the task immediately after the first task is completed in 20 seconds.
But the Timer.scheduleAtFixedRate method also behaves in the same way. This is what is in the documentation:
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.".
I expect that multiple threads will be spun to catch up, but this is not happening.
How can this be explained? What is a good example to demonstrate the difference between these methods?
Java documentation for the Timer class:
Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. 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.
The expectation that additional threads will be created to catch up is incorrect. According to the documentation, Timer tasks should complete quickly. A Timer task should not take 20 seconds to complete. An alternative is the ScheduledThreadPoolExecutor class:
A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.
To answer the second question: The difference is that the schedule method "schedules the specified task for repeated fixed-delay execution" and the
scheduleAtFixedRate method "schedules the specified task for repeated fixed-rate execution". This answer explains this difference well.
yes,Java Timer object can be created to run the associated tasks as a daemon thread.
https://www.geeksforgeeks.org/java-util-timer-class-java/
Can anybody explain me What is difference between scheduleAtFixedRate() and schedule() methods in Timer Class with simple code example.
The schedule(TimerTask task,long delay,long period) method is used to schedule the specified task for repeated fixed-delay execution, beginning after the specified delay.
The scheduleAtFixedRate(TimerTask task,long delay,long period) method is used to schedule the specified task for repeated fixed-rate execution, beginning after the specified delay
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.
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)
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.