ScheduledExecutorService 将返回一个 Future,它有一个额外的方法来检查 Runnable 是否完成。两者都有取消 Runnable 的方法。对于像这样的重复任务,检查它是否完成,可能不会有太大用处。但是,它是由 jdk 1.5 并发 api 引入的,它绝对应该用来代替旧的并发/线程 api(Timer 和 TimerTask 是 jdk 1.3)。它们将更健壮,性能更好。他们在此处的 java doc 中有一个与您的用例非常相似的示例。
这是一个示例:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class ScheduledTaskExample {
private final ScheduledExecutorService scheduler = Executors
.newScheduledThreadPool(1);
public void startScheduleTask() {
/**
* not using the taskHandle returned here, but it can be used to cancel
* the task, or check if it's done (for recurring tasks, that's not
* going to be very useful)
*/
final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(
new Runnable() {
public void run() {
try {
getDataFromDatabase();
}catch(Exception ex) {
ex.printStackTrace(); //or loggger would be better
}
}
}, 0, 15, TimeUnit.MINUTES);
}
private void getDataFromDatabase() {
System.out.println("getting data...");
}
public void shutdowh() {
System.out.println("shutdown...");
if(scheduler != null) {
scheduler.shutdown();
}
}
public static void main(String[] args) {
final ScheduledTaskExample ste = new ScheduledTaskExample();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
ste.shutdowh();
}
});
ste.startScheduleTask();
}
}