定时任务Demo总结(推荐最后一种)
创始人
2024-05-21 05:03:12
0

方法一: 线程实现 Runnable 接口

    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();

测试:

在这里插入图片描述

方法二:自定义实现 Runnable 接口(本质上也是实现了 Runnable)

    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();}}}}

测试:
在这里插入图片描述

方法三: Timer: JDK 自带的定时任务类。 优点: 使用方便。

 //定义一个定时任务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);}}

方法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

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...