Thread thread = new Thread(new Runnable() {@Overridepublic 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();
测试:
MyRunnable myRunnable = new MyRunnable();Thread thread = new Thread(myRunnable);thread.start();/*** 自定义类MyRunnable实现java.lang.Runnable接口*/class MyRunnable implements Runnable {@Overridepublic 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();}}}}
测试:
//定义一个定时任务TimerTask timerTask = new TimerTask() {@Overridepublic 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() {@Overridepublic 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);}}
写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
下一篇:Java集合常见面试题(五)