我尝试了一些代码来实现一个预定的任务,并想出了这些代码。
import java.util.*;
class Task extends TimerTask {
int count = 1;
// run is a abstract method that defines task performed at scheduled time.
public void run() {
System.out.println(count+" : Mahendra Singh");
count++;
}
}
class TaskScheduling {
public static void main(String[] args) {
Timer timer = new Timer();
// Schedule to run after every 3 second(3000 millisecond)
timer.schedule( new Task(), 3000);
}
}我的输出:
1 : Mahendra Singh我期望编译器以3s的周期间隔打印一系列Mahendra Singh,但是尽管等待了大约15分钟,我只得到了一个output...How,我能解决这个问题吗?
发布于 2010-12-28 16:01:03
使用timer.scheduleAtFixedRate
public void scheduleAtFixedRate(TimerTask task,
long delay,
long 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). 固定速率执行适用于对绝对时间敏感的重复性活动,例如每小时在整点振铃,或在每天的特定时间运行计划维护。它还适用于执行固定数量的执行的总时间很重要的循环活动,例如,倒计时计时器每秒计时一次,持续十秒。最后,固定速率执行适用于调度多个重复计时器任务,这些任务必须彼此保持同步。
参数:
task - task task to be scheduled.
抛出:
发布于 2010-12-28 17:11:21
ScheduledExecutorService相对于Timer的优势
我希望为您提供一个使用- ScheduledThreadPoolExecutor的Timer替代方案,它是ScheduledExecutorService接口的一个实现。根据"Java in Concurrency“的说法,它比Timer类有一些优势:
Timer只创建一个线程来执行计时器任务。如果计时器任务运行时间太长,其他TimerTask的计时精度可能会受到影响。如果一个循环任务被安排为每10毫秒运行一次,而另一个计时器任务需要40毫秒才能运行,则循环任务(取决于它是以固定速率还是固定延迟调度的)在长时间运行的任务完成后被快速连续调用四次,或者完全“错过”四次调用。调度线程池允许您为执行延迟和定期任务提供多个线程,从而解决了这一限制。
Timer的另一个问题是,如果TimerTask 抛出未检查的异常,它的行为会很糟糕。也称为“线程泄漏”
计时器线程不会捕获异常,因此从
TimerTask抛出的未检查的异常将终止计时器线程。在这种情况下,Timer也不会复活线程;相反,它错误地认为整个计时器都被取消了。在这种情况下,已调度但尚未执行的TimerTasks永远不会运行,并且无法调度新任务。
另一个建议是,如果您需要构建自己的调度服务,您仍然可以通过使用DelayQueue (提供ScheduledThreadPoolExecutor的调度功能的BlockingQueue实现)来利用该库。DelayQueue管理延迟对象的集合。Delayed有一个与之相关的延迟时间:DelayQueue允许您仅在元素的延迟过期时才获取该元素。对象从DelayQueue返回,按与其延迟相关的时间排序。
发布于 2010-12-28 14:54:33
public void schedule(TimerTask task,long delay)安排指定的任务在指定的延迟后执行。
您需要:
public void schedule(TimerTask task, long delay, long period)从指定延迟之后开始,为重复执行固定延迟调度指定的任务。后续执行大约以固定的间隔进行,间隔为指定的时间段。
https://stackoverflow.com/questions/4544197
复制相似问题