定时任务:表示根据设定的某个时间频率,重复不断地被执行的某个任务。应用场景:定时获取一个数据库中的数据,并同步到其他数据库中;“定时查询即将过期失效的订单,并对其做失效处理”
1.写一个@Component 注解的类,使用@Scheduled(cron=“cron表达式”)注解的方法。如@Scheduled(cron = “0/5 * * * * ?”)
2. Spring Boot启动程序上,添加@EnableScheduled:“开启定时任务调度”
1.新建项目 spring-boot-scheduled
2.pom文件如下,引入spring-boot-starter-web 2.3.5.RELEASE,完整的l如下:
<?xml version="1.0" encoding="UTF-8"?><project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.dreamli</groupId><artifactId>spring-boot-scheduled</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><name>spring-boot-scheduled Maven Webapp</name><!-- FIXME change it to the project's website --><url>;/url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><mavenpiler.source>1.8</mavenpiler.source><mavenpiler.target>1.8</mavenpiler.target></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.3.5.RELEASE</version></dependency></dependencies>
</project>
3.核心配置文件 l
server:port: 9090servlet:context-path: /schedule-task
4.启动类
package com.dreamli;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;/*** @Title Application.class* @Package com.dreamli* @Description 启动类* @Author zhaoml* @DateTime 2023/3/8 16:38* @Version V1.0*/
@SpringBootApplication
//开启定时任务调度
@EnableScheduling
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class,args);}
}
5.定时任务类
package com.dreamli.scheduleTask;import t.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;/*** @Title ScheduledDemo.class* @Package com.dreamli.scheduleTask* @Description 简单单线程定时任务* @Author zhaoml* @DateTime 2023/3/8 16:42* @Version V1.0*/
@Component
public class ScheduledDemo {// cron表达式的含义:从0秒开始,每5秒,控制台输出一次// 在线cron 表达式生成器,/@Scheduled(cron = "0/5 * * * * ?")public void simpleSingleThreadScheduledTask(){System.out.println(System.currentTimeMillis()+"每5秒,执行一次的定时任务");}
}
本文发布于:2024-02-04 13:42:00,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170708536556075.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |