前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot简单定时任务

Spring Boot简单定时任务

作者头像
背雷管的小青年
发布2020-06-09 15:27:29
4110
发布2020-06-09 15:27:29
举报
文章被收录于专栏:技术开发——你我他

目标:实现springboot的简单的定时任务 工具:IDEA--2020.1 学习目标:实现springboot的简单的定时任务 本次学习的工程下载链接放到文本最后面

  • 首先创建一个springboot项目 先在启动类上打上注解@EnableScheduling
代码语言:javascript
复制
> package com.xmaven;
> 
> import org.springframework.boot.SpringApplication; import
> org.springframework.boot.autoconfigure.SpringBootApplication; import
> org.springframework.scheduling.annotation.EnableScheduling;
> 
> @SpringBootApplication //添加 @EnableScheduling 注解,开启对定时任务的支持
> @EnableScheduling 
> public class SpringbootScheduledApplication {
> 
>     public static void main(String[] args) {
>         SpringApplication.run(SpringbootScheduledApplication.class, args);
>     }
> 
> }

创建一个简单的任务类:

package com.xmaven.task;

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

import java.time.LocalDateTime;

@Component public class ScheduledTask {

代码语言:javascript
复制
@Scheduled(fixedRate = 3000)
public void scheduledTask(){
    System.out.println("任务执行时间:" + LocalDateTime.now());
}

}

  • 演示结果如下:
)VZZA()O0JF_XT3MF074SLU.png
)VZZA()O0JF_XT3MF074SLU.png
  • @Scheduled详解
  • @Scheduled(fixedRate = 3000) :上一次开始执行时间点之后 3 秒再执行(fixedRate属性:定时任务开始后再次执行定时任务的延时(需等待上次定时任务完成),单位毫秒)
  • @Scheduled(fixedDelay =3000) :上一次执行完毕时间点之后 3 秒再执行(fixedDelay属性:定时任务执行完成后再次执行定时任务的延时(需等待上次定时任务完成),单位毫秒)
  • @Scheduled(initialDelay=1000, fixedRate = 3000) :第一次延迟1秒后执行,之后按fixedRate的规则每3秒执行一次(initialDelay 属性:第一次执行定时任务的延迟时间,需配合fixedDelay或者fixedRate来使用)
  • @Scheduled(cron="0 0 2 1 ? ") :通过cron表达式定义规则

其中,常用的cron表达式有:

代码语言:javascript
复制
0 0 2 1 * ? * :表示在每月 1 日的凌晨 2 点执行
0 15 10 ? * MON-FRI :表示周一到周五每天上午 10:15 执行
0 15 10 ? 6L 2019-2020 :表示 2019-2020 年的每个月的最后一个星期五上午 10:15 执行
0 0 10,14,16 * * ? :每天上午 10 点,下午 2 点,4 点执行
0 0/30 9-17 * * ? :朝九晚五工作时间内每半小时执行
0 0 12 ? * WED :表示每个星期三中午 12 点执行
0 0 12 * * ? :每天中午 12点执行
0 15 10 ? * * :每天上午 10:15 执行
0 15 10 * * ? :每天上午 10:15 执行
0 15 10 * * ? * :每天上午 10:15 执行
0 15 10 * * ? 2019 :2019 年的每天上午 10:15 执行
  • 总结 主程序入口 @EnableScheduling 开启定时任务 定时方法上 @Scheduled 设置定时 cron属性:按cron规则执行 fixedRate 属性:以固定速率执行 fixedDelay 属性:上次执行完毕后延迟再执行 initialDelay 属性:第一次延时执行,第一次执行完毕后延迟后再次执行

下载链接:springboot-scheduled.rar

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档