Spring Task(简略笔记)

介绍

Spring Task是Spring框架提供的任务调度工具,可以按照约定的时间自动执行某个代码逻辑。

Corn表达式

corn表达式其实就是一个字符串,通过corn表达式可以定有任务触发的时间

构成规则:分为6或7个域,由空格分隔开,每个域代表一个含义

每个域的含义分别为:秒,分钟,小时,日,月,周,年(可选)

表达式网站

在线Cron表达式生成器

" https://cron.qqe2.com/ "

使用步骤

启动类加上:

复制代码
@EnableScheduling  //开启任务调度
java 复制代码
@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@Slf4j
@EnableCaching //开启缓存注解功能
@EnableScheduling  //开启任务调度
public class SkyApplication {
    public static void main(String[] args) {
        SpringApplication.run(SkyApplication.class, args);
        log.info("server started");
    }
}
java 复制代码
package com.sky.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Mtz
 * @version 1.0
 * @2023/9/2010:41
 * @function
 * @comment
 */
@Component
@Slf4j
public class MyTask {

    /*
    定时任务
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void executeTask() {
        log.info("定时任务开始执行:{}", new Date());
    }

}
相关推荐
日月云棠3 小时前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840824 小时前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide4 小时前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家5 小时前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java
花花无缺5 小时前
搞懂new 关键字(构造函数)和 .builder() 模式(建造者模式)创建对象
java
用户908324602735 小时前
Spring Boot + MyBatis-Plus 多租户实战:从数据隔离到权限控制的完整方案
java·后端
桦说编程5 小时前
实战分析 ConcurrentHashMap.computeIfAbsent 的锁冲突问题
java·后端·性能优化
玹外之音7 小时前
Spring AI MCP 实战:将你的服务升级为 AI 可调用的智能工具
spring·ai编程
来一斤小鲜肉8 小时前
Spring AI入门:第一个AI应用跑起来
spring·ai编程
NE_STOP9 小时前
springMVC-常见视图组件与RESTFul编程风格
spring