Timer计时器有管理任务延迟执行("如1000ms后执行任务")以及周期性执行("如每500ms执行一次该任务")。但是,Timer存在一些缺陷,因此你应该考虑使用ScheduledThreadPoolExecu tor作为代替品,Timer对调度的支持是基于绝对时间,而不是相对时间的,由此任务对系统时钟的改变是敏感的;ScheduledThreadExecutor只支持相对时间。
但是ScheduledThreadPoolExecu
tor也有不利的地方,就是只能按相对的时间的,而不能设置具体某个时刻之后执行,如每天晚上12点定时执行任务之类的要求使用Timer更合适,如果是周期性的重复工作可以考虑使用ScheduledThreadPoolExecu
tor。另外也可以
Quartz框架实现定时作业的功能。
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
private Timer timer = new Timer();
// 启动计时器
public void lanuchTimer() {
timer.schedule(new TimerTask() {
public void run() {
System.out.println("计时器启动");
throw new RuntimeException();
}
}, 1000 * 3, 500);
}
// 向计时器添加一个任务
public void addOneTask() {
timer.schedule(new TimerTask() {
public void run() {
System.out.println("hello world");
}
}, 1000 * 1, 1000 * 5);
}
public static void main(String[] args) throws Exception {
TimerTest test = new TimerTest();
test.lanuchTimer();
Thread.sleep(1000 * 5);// 5秒钟之后添加一个新任务
test.addOneTask();
}
}
执行结果:
你可能希望第二个没有异常的线程会一直运行下去,然而实际情况如程序所示5秒钟后就中止了,还伴随着一个异常,异常的消息是"Timer already cancelled"。ScheduledThreadPoolExect
java5.0后提供
-
public interface ScheduledExecutorService
extends
ExecutorService
一个 ExecutorService
,可安排在给定的延迟后运行或定期执行的命令。
schedule 方法使用各种延迟创建任务,并返回一个可用于取消或检查执行的任务对象。scheduleAtFixedRate 和scheduleWithFixedDelay 方法创建并执行某些在取消前一直定期运行的任务。
而且不受时钟限制。
例子:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorTest {
/**
* 线程池能按时间计划来执行任务,允许用户设定计划执行任务的时间,int类型的参数是设定
* 线程池中线程的最小数目。当任务较多时,线程池可能会自动创建更多的工作线程来执行任务
*/
public ScheduledExecutorService scheduExec = Executors.newScheduledThreadPool(1);
// 启动计时器
public void lanuchTimer() {
Runnable task = new Runnable() {
public void run() {
System.out.println("计时器1启动");
throw new RuntimeException();
}
};
//创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。
scheduExec.scheduleWithFixedDelay(task, 1000 * 5, 1000 * 30, TimeUnit.MILLISECONDS);
}
// 添加新任务
public void addOneTask() {
Runnable task = new Runnable() {
public void run() {
System.out.println("计时器2启动");
}
};
scheduExec.scheduleWithFixedDelay(task, 1000 * 1, 1000*10, TimeUnit.MILLISECONDS);
}
public static void main(String[] args) throws Exception {
ScheduledExecutorTest test = new ScheduledExecutorTest();
test.lanuchTimer();
Thread.sleep(1000 * 5);// 5秒钟之后添加新任务
test.addOneTask();
}
}
但是ScheduledThreadPoolExecu