栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot-定时任务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot-定时任务

前言

定时任务SpringBoot默认已经帮我们实行了,只需要添加相应的注解就可以实现。

SpringBoot整合定时任务其实就两点:
1.创建一个能被定时任务类,方法上加入@Scheduled注解
2.在启动类application上加入@EnableScheduling注解

pom文件

只需要引入 Spring Boot Starter 包即可



    4.0.0

    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.6.RELEASE
         
    

    com.huzh
    springboot-scheduled
    0.0.1-SNAPSHOT

    springboot-scheduled
    springboot-scheduled

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.springframework.boot
            spring-boot-devtools
            runtime
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

application类启用定时

在启动类上面加上@EnableScheduling即可开启定时

@SpringBootApplication
@EnableScheduling
public class SpringbootScheduledApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootScheduledApplication.class, args);
    }
}
创建定时任务类TestTimer
  1. @Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。
  2. @Scheduled开启定时
@Component
public class TestTimer {

    @Scheduled(cron = "0/1 * * * * ?")
    private void test() {
        System.out.println("执行定时任务的时间是" + new Date());
    }
}
备注

需要注意的是@Scheduled(cron = “0/1 * * * * ?”)中cron的值根据自己实际需要去写,可参考http://cron.qqe2.com/

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946963.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号