方法一: 线程实现 Runnable 接口
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
String dateStr = sdf.format(new Date());
System.out.println("线程等待实现定时任务:" + dateStr);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
测试:
方法二:自定义实现 Runnable 接口(本质上也是实现了 Runnable)
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
/**
* 自定义类MyRunnable实现java.lang.Runnable接口
*/
class MyRunnable implements Runnable {
@Override
public void run() {
while (true) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
String dateStr = sdf.format(new Date());
System.out.println("线程等待实现定时任务1:" + dateStr);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试:
方法三: Timer: JDK 自带的定时任务类。 优点: 使用方便。
//定义一个定时任务
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
String dateStr = sdf.format(new Date());
System.out.println("运行定时任务:" + dateStr);
}
};
//计时器
Timer timer = new Timer();
//添加执行任务,延迟 delay 开始执行任务、 每 3s 执行一次
// timer.schedule(timerTask, new Date(), 3000);
// 添加执行任务,延迟 5s 开始执行 ,然后每隔一分钟执行一次
Date date = new Date();
//每分钟执行一次定时任务
timer.scheduleAtFixedRate(timerTask,date, 60000);
测试:
举例: 每天的固定时间执行任务
```java
/**
* Thread 线程的等待
*/
public static void main(String[] args) {
final int[] count = {1};
TimerTask task = new TimerTask() {
@Override
public void run() {
//此处编写需要进行定时执行的任务;
count[0] = count[0] + 1;
System.out.println("时间=" + new Date() + " 执行了" + count[0] + "次"); // 1次
}
};
//设置执行时间
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
//定制每天的23:00:00执行,
calendar.set(year, month, day, 15, 17, 00);
Date date = calendar.getTime();
Timer timer = new Timer();
System.out.println(date);
//每天的date时刻执行task,每隔2秒重复执行
int period = 2 * 1000;
//timer.schedule(task, date, period);
//每天的date时刻执行task, 仅执行一次
timer.schedule(task, date);
}
}
方法4: Spring 的定时任务:注解式定时任务
写Spring 定时任务相关的demo
@Component
@Slf4j
public class SpringTaskDemo {
@Scheduled(cron = "0/5 * * * * *")
public void scheduled(){
log.info("=====>>>>>使用cron {}",System.currentTimeMillis());
}
@Scheduled(fixedRate = 5000)
public void scheduled1() {
log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis());
}
@Scheduled(fixedDelay = 5000)
public void scheduled2() {
log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis());
}
}
主类中开启定时任务的注解/ 在需要定时器的类上加注解
spring 定时任务参考博客:https://blog.csdn.net/weixin_44768683/article/details/125702724*
视频学习地址:https://www.bilibili.com/video/BV1xJ411G7ff
源码解析:https://mp.weixin.qq.com/s/CBAzqoSAG1QJhfZBEuPtlg