Timer和TimerTask通过单线程调度定时任务,适合轻量级、短时任务,但异常或长任务会阻塞或终止整个调度;应优先使用ScheduledThreadPoolExecutor,因其支持多线程、异常隔离和更灵活的调度,提升系统健壮性。

在Java中,
Timer
TimerTask
使用
Timer
TimerTask
Timer
TimerTask
run()
Timer
schedule()
scheduleAtFixedRate()
一个简单的例子,如果你想让某个操作每隔5秒执行一次,可以这么做:
import java.util.Timer;
import java.util.TimerTask;
public class MyScheduledTask extends TimerTask {
private int counter = 0;
@Override
public void run() {
System.out.println("任务执行了!当前计数: " + (++counter) + " - 线程: " + Thread.currentThread().getName());
// 模拟一些可能出错的逻辑
if (counter == 3) {
System.out.println("模拟一个运行时异常发生...");
throw new RuntimeException("任务在第三次执行时失败了!");
}
}
public static void main(String[] args) {
Timer timer = new Timer("MyCustomTimerThread", true); // 设置为守护线程
MyScheduledTask task = new MyScheduledTask();
// 延迟1秒后开始,每5秒执行一次
timer.scheduleAtFixedRate(task, 1000, 5000);
System.out.println("定时器已启动,等待任务执行...");
// 模拟主线程做其他事情,或者等待一段时间后关闭timer
try {
Thread.sleep(20000); // 让任务执行几次
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
timer.cancel(); // 停止所有未执行的任务并终止Timer线程
System.out.println("定时器已取消。");
}
}这里需要注意几点:
Timer
Timer
true
Timer
scheduleAtFixedRate
schedule
scheduleAtFixedRate
立即学习“Java免费学习笔记(深入)”;
Timer
TaskQueue
TimerTask
Timer-n
我发现很多初学者,包括我自己当年,都容易忽略一个关键点:
Timer
TimerTask
TimerTask
run()
Timer
Timer
所以,
Timer
TimerTask
run()
如果你面对的是复杂的、耗时的、或者需要高并发处理的定时任务,那
Timer
关于
TimerTask
TimerTask
当
TimerTask
run()
RuntimeException
NullPointerException
ArrayIndexOutOfBoundsException
Timer
Timer
为了避免这种情况,务必在TimerTask
run()
try-catch
class RobustTimerTask extends TimerTask {
@Override
public void run() {
try {
// 你的业务逻辑代码
System.out.println("执行任务中...");
// 模拟一个可能失败的操作
if (System.currentTimeMillis() % 2 == 0) {
throw new IOException("模拟文件写入失败");
}
} catch (IOException e) {
System.err.println("任务执行异常: " + e.getMessage());
// 这里可以进行日志记录、报警通知等
} catch (Exception e) { // 捕获其他所有可能的运行时异常
System.err.println("捕获到未预期的异常: " + e.getMessage());
// 同样进行日志记录和报警
}
}
}至于生命周期,
TimerTask
schedule
Timer
cancel()
Timer
TimerTask
Timer
cancel()
cancel()
Timer
cancel()
TimerTask
考虑到
Timer
java.util.concurrent.ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor
Runnable
Callable
Future
下面是一个使用
ScheduledThreadPoolExecutor
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class MyScheduledExecutorTask {
private static int counter = 0;
public static void main(String[] args) {
// 创建一个包含1个线程的调度线程池
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
try {
System.out.println("任务执行了!当前计数: " + (++counter) + " - 线程: " + Thread.currentThread().getName());
// 模拟一些可能出错的逻辑
if (counter == 3) {
System.out.println("模拟一个运行时异常发生...");
throw new IOException("任务在第三次执行时失败了!"); // 抛出异常
}
} catch (IOException e) {
System.err.println("ScheduledExecutorService 任务执行异常: " + e.getMessage());
// 异常会被捕获并打印,但调度器不会停止
} catch (Exception e) {
System.err.println("ScheduledExecutorService 捕获到未预期的异常: " + e.getMessage());
}
};
// 延迟1秒后开始,每5秒执行一次
ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(task, 1, 5, TimeUnit.SECONDS);
System.out.println("调度器已启动,等待任务执行...");
try {
Thread.sleep(20000); // 让任务执行几次
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
future.cancel(false); // 尝试取消任务,false表示不中断正在运行的任务
scheduler.shutdown(); // 关闭调度器,等待所有任务完成
System.out.println("调度器已关闭。");
}
}对比一下,你会发现
ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor
Timer
以上就是Java中Timer和TimerTask使用技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号