SpringBoot实现定时任务@EnableScheduling

JAVA小咖秀

共 1428字,需浏览 3分钟

 · 2020-10-30

来源:http://blog.csdn.net/weixin_42949841/article/details/108695570

1. 新建项目,在pom.xml导入必要的依赖。

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


    
        
        
            org.springframework.boot
            spring-boot-starter-web
        

    


2. 写一个SpringBoot的启动类

  • 启动类里面使用@EnableScheduling 注解开启定时任务功能。

@SpringBootApplication
@EnableScheduling
@MapperScan("com.less.parent.dao")
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

3. 编写定时任务

  • 要在任务的类上写@Component,将当前的任务类注入到容器。

  • 要在任务方法上写@Scheduled,然后编写cron表达式。

@Component
public class SchedulingTask {
    
    //表示每隔3秒
    // @Scheduled(fixedRate = 3000)
    
    // 表示方法执行完成后5秒
    // @Scheduled(fixedDelay = 5000)
    
    // 表示每五秒执行一次
    @Scheduled(cron = "*/5 * * * * ?")
    public void TestTask() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(dateFormat.format(new Date()));
    }
}

4. 执行结果

2020-09-20 17:20:35
2020-09-20 17:20:40
2020-09-20 17:20:45

5. 总结

  • fixedDelay和fixedRate,单位是毫秒,这里这里就是5秒和3秒,它们的区别就是:fixedRate就是每多次分钟一次,不论你业务执行花费了多少时间。我都是1分钟执行1次,而fixedDelay是当任务执行完毕后1分钟在执行。所以根据实际业务不同,我们会选择不同的方式。

  • cron表达式:比如你要设置每天什么时候执行,就可以用它不会写的话,网上有专门的语法,可以单独去查。


-END-


SSM框架权限系统脚手架教程(资料全)

加我微信回复“SSM框架权限”即可获取

点个在看?

谢谢支持哟 (*^__^*)

浏览 33
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报