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

SpringBoot定时任务

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

SpringBoot定时任务

项目中很多时候会使用到定时任务,这篇文章介绍一下springboot整合定时任务。

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

代码如下,pom文件我只加入了devtools,其实不加入也可以



    4.0.0

    com.dalaoyang
    springboot_scheduled
    0.0.1-SNAPSHOT
    jar

    springboot_scheduled
    springboot_scheduled

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

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        

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

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


application类代码如下:

package com.dalaoyang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SpringbootScheduledApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootScheduledApplication.class, args);
    }
}

定时任务类TestTimer

package com.dalaoyang.timer;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;


@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/235355.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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