定时任务简单来说就是在指定时间,以指定的频率来执行一个方法,而在 Java 中我们又该如何实现呢?
今天介绍的都是最原始的方式,开启一个线程,让它睡一会跑一次这也就达到了定频率的执行 run 方法,我们只需要将业务逻辑写在 run 方法中即可。
import java.util.Date;
public class ThreadTest {
public static void main(String[] args) {
// 设置执行周期 final long timeInterval = 3000;
Runnable runnable = new Runnable() {
public void run() {
while (true) {
System.out.println("Task Run ... " + new Date());
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
我想使用线程来执行定时任务应该是所有牛逼定时器的核心所在了吧,下面介绍一种用起来更加顺手的方式 Timer 定时器。
Timer 定时器可以简单的理解为有且仅有一个后台线程对多个业务方法进行