spring Task 定时任务


导入maven坐标 spring-context(已存在)

复制代码
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.34</version> <!-- 请根据需要选择合适的版本 -->
</dependency>

启动类添加注解 @EnableScheduling 开启任务调度在这里插入代码片

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

server层下面创建一个task包,在包下面创建一个定时任务类

复制代码
package com.sky.task;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
import java.util.Date;
 
/**
 * 自定义定时任务类
 */
@Component //交给IOC容器管理
@Slf4j
public class MyTask {
 
    /**
     * 定时任务 每隔5秒触发一次
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void executeTask(){ //方法名任意
        log.info("定时任务开始执行:{}",new Date());
    }
}
相关推荐
秋天的怀念_David1 天前
算法一千零一夜 · 第三十五夜 · 恢复风暴
java·程序人生·算法
考虑考虑1 天前
JDK27中的加密对象的 PEM 编码
java·后端·java ee
Coder_shen1 天前
汇川 EVO 系列 PLC EtherNet/IP(CIP)协议通信驱动的 C# 实现
后端
行百里er1 天前
【Spring Insight 技术分享】如何让 AI 解释失败也不拖垮控制台
后端·spring cloud·开源
行者-全栈开发1 天前
SpringBoot + GraalVM 原生编译实战:启动时间从8秒到0.5秒的极致优化
java·spring boot·后端
CoderYanger1 天前
Java EE 进阶:10. MyBatis-Plus使用(第一弹)
java·spring boot·后端·sql·spring·java-ee·mybatis
一条Go1 天前
状态页与 SLA:对外承诺是怎么算出来的
后端·架构·github
喵个咪1 天前
GoWind IM 场景:乙方怎么用一套 IM 平台交付多个客户——档位、租户与离线交付
后端·go·saas
大胖爱学习_MJ1 天前
超越向量检索:用 Spring Boot + Neo4j 手搓 GraphRAG 知识图谱记忆
java·后端·python
吃我一窝jio1 天前
Java博客极简写作三支柱
java