spring定时任务

【一】Spring的@schedule注解实现定时任务

项目经常会用到定时任务,实现定时任务的方式有很多种。在Spring框架中,实现定时任务很简单,常用的实现方式是使用注解@Schedule。

@Schedule 常用来实现简单的定时任务。例如凌晨1点跑批,每1小时更新订单状态等


使用篇

一、Spring项目

1、在spring.xml(或applicationContext.xml,以自己的配置文件名为准)中添加配置

<!-- 1、在 xmlns中加入 -->
xmlns:task="http://www.springframework.org/schema/task"

<!-- 2、 在xsi:schemaLocation中加入 -->
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd"

<!— 3、 配置spring扫描注解的路径 -->
<context:component-scan base-package=“com.it.mytask” />

<!-- 4、 定时任务扫描配置 -->
<!-- 4.1、 方式一: -->
<task:executor id=“executor” pool-size=“5” />
<task:scheduler id=“scheduler” pool-size=“10” />
<task:annotation-driven executor=“executor” scheduler=“scheduler” />

<!-- 4.2、 方式二:–>
<task:annotation-driven scheduler=“scheduler” mode=“proxy”/>
<task:scheduler id=“scheduler” pool-size=“10”/>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
		http://www.springframework.org/schema/tx 		
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/task 
		http://www.springframework.org/schema/task/spring-task-3.0.xsd"
	default-lazy-init="false">
&lt;context:annotation-config /&gt;

&lt;!—  配置spring扫描注解的路径   --&gt;
&lt;context:component-scan base-package="com.it.mytask" /&gt;

&lt;!-- 定时任务扫描配置 --&gt;
&lt;!— 开启这个配置,spring才能识别@Scheduled注解   --&gt;
&lt;task:annotation-driven scheduler="scheduler" mode="proxy"/&gt;
&lt;task:scheduler id="scheduler" pool-size="10"/&gt;

</beans>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

2、任务类(官网给出简单的例子)

@Component
public class ScheduleTask {
// 每隔5秒执行一次
@Scheduled(cron = "0/5 * * * * ?")
public void printSay() {
    System.out.println("每隔5秒执行一次:" + new Date());
}

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
二、SpringBoot项目

1、任务类同上

2、Application:

@SpringBootApplication
@EnableScheduling  // 在spring boot的入口类Application.java中,允许支持schedule
public class Application {
public static void main(String[] args) throws Exception {
    SpringApplication.run(Application.class);
}

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3、结果
在这里插入图片描述


原理篇

一、@Scheduled源码
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
    String cron() default "";
String zone() default "";

long fixedDelay() default -1L;

String fixedDelayString() default "";

long fixedRate() default -1L;

String fixedRateString() default "";

long initialDelay() default -1L;

String initialDelayString() default "";

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

案例

package com.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTask {
private Logger logger= LoggerFactory.getLogger(ScheduledTask.class);

// fixedRate = 5000表示每隔5秒,Spring scheduling会调用一次该方法,不论该方法的执行时间是多少
@Scheduled(fixedRate = 5000)
public void task() {
    logger.info("每隔5秒执行一次");
}

// fixedDelay = 5000表示当方法执行完毕5秒后,Spring scheduling会再次调用该方法
@Scheduled(fixedDelay = 5000)
public void taskAfter() {
    logger.info("当方法执行完毕5秒后执行");
}

// cron = "*/5 * * * * * *" 通用的定时任务表达式,表示每隔5秒执行一次
@Scheduled(cron = "*/5 * * * * *")
public void taskCron() {
    logger.info("每隔5秒执行一次");
}

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
二、cron 表达式
  1. cron一共有7位,但是最后一位是年(1970-2099),可以留空,所以我们可以写6位,按顺序依次为
  • 秒(0~59)
  • 分钟(0~59)
  • 小时(0~23)
  • 天(月)(0~31,但是你需要考虑你月的天数)
  • 月(0~11)
  • 星期(1~7 1=SUN,MON,TUE,WED,THU,FRI,SAT)
  1. cron的一些特殊符号
  • (*)星号:
    可以理解为每的意思,每秒,每分,每天,每月,每年…
  • (?)问号:
    问号只能出现在日期和星期这两个位置,表示这个位置的值不确定,每天3点执行,所以第六位星期的位置,我们是不需要关注的,就是不确定的值。同时:日期和星期是两个相互排斥的元素,通过问号来表明不指定值。比如,1月10日,比如是星期1,如果在星期的位置是另指定星期二,就前后冲突矛盾了。
  • (-)减号:
    表达一个范围,如在小时字段中使用“10-12”,则表示从10到12点,即10,11,12
  • (,)逗号:
    表达一个列表值,如在星期字段中使用“1,2,4”,则表示星期一,星期二,星期四
    (/)斜杠:如:x/y,x是开始值,y是步长,比如在第一位(秒) 0/15就是,从0秒开始,每15秒,最后就是0,15,30,45,60 另:*/y,等同于0/y

eg.下面列举几个例子供大家来验证:

0 0 3 * * ?  每天3点执行
0 5 3 * * ?  每天3点5分执行
0 5 3 ? * *  每天3点5分执行,与上面作用相同
0 5/10 3 * * ?  每天3点的 5分,15分,25分,35分,45分,55分这几个时间点执行
0 10 3 ? * 1  每周星期天,3点10分 执行,注:1表示星期天
0 10 3 ? * 1#3  每个月的第三个星期,星期天 执行,#号只能出现在星期的位置

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

常用示例:
格式: [秒] [分] [小时] [日] [月] [周] [年]

0 0 12 * * ?           每天12点触发 
0 15 10 ? * *          每天10点15分触发 
0 15 10 * * ?          每天10点15分触发  
0 15 10 * * ? *        每天10点15分触发  
0 15 10 * * ? 2005     2005年每天10点15分触发 
0 * 14 * * ?           每天下午的 2点到2点59分每分触发 
0 0/5 14 * * ?         每天下午的 2点到2点59分(整点开始,每隔5分触发)  
0 0/5 14,18 * * ?        每天下午的 18点到18点59分(整点开始,每隔5分触发)
0 0-5 14 * * ?            每天下午的 2点到2点05分每分触发 
0 10,44 14 ? 3 WED        3月分每周三下午的 2点10分和2点44分触发 
0 15 10 ? * MON-FRI       从周一到周五每天上午的10点15分触发 
0 15 10 15 * ?            每月15号上午10点15分触发 
0 15 10 L * ?             每月最后一天的10点15分触发 
0 15 10 ? * 6L            每月最后一周的星期五的10点15分触发 
0 15 10 ? * 6L 2002-2005  从2002年到2005年每月最后一周的星期五的10点15分触发
0 15 10 ? * 6#3           每月的第三周的星期五开始触发 
0 0 12 1/5 * ?            每月的第一个中午开始每隔5天触发一次 
0 11 11 11 11 ?           每年的11月11号 11点11分触发(光棍节)

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
                                </div>
            <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e44c3c0e64.css" rel="stylesheet">
                </div>
</article>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值