项目依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gmy</groupId>
<artifactId>mybatis-springboot</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
</parent>
<dependencies>
<!-- spring-boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
配置文件
# 日志相关配置
logging:
level:
root: debug
debug: true
增加配置类
package com.gmy.mybatis.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author gmy
* @date 2023/7/8 14:51
*/
@Configuration
@EnableScheduling
public class ScheduleConfig {
}
@EnableScheduling
:开启定时任务功能
创建定时任务
要求:每隔5s控制台输出hello world
cron
package com.gmy.mybatis.schedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author gmy
* @date 2023/7/8 14:53
*/
@Slf4j
@Component
public class PrintSchedule {
@Scheduled(cron = "*/5 * * * * *")
public void printMessage() {
log.debug("hello world");
}
}
@Slf4j
:便捷地进行日志输出
@Component
:定义为bean,交给Spring管理
@Scheduled
:定义执行的时间
cron表达式参考cron表达式详解