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

版权声明:分享知识是一种快乐,愿你我都能共同成长! https://blog.csdn.net/qidasheng2012/article/details/84386662

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

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


非SpringBoot项目
在springmvc-servlet.xml中添加配置

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

<!-- xsi:schemaLocation中加入 -->
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.0.xsd"
    
<!-- 定时任务扫描配置 -->
<!-- 方式一: -->
<task:executorid="executor" pool-size="5" /> 
<task:schedulerid="scheduler" pool-size="10" /> 
<task:annotation-drivenexecutor="executor" scheduler="scheduler" />

<!-- 方式二:-->
<task:annotation-driven scheduler="scheduler" mode="proxy"/>
<task:scheduler id="scheduler" pool-size="10"/>

<?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">

	<context:annotation-config />
	<!— spring扫描注解的配置   -->
	<context:component-scan base-package="com.it.mytask" />
	
	<!—开启这个配置,spring才能识别@Scheduled注解   -->
	<task:annotation-driven scheduler="scheduler" mode="proxy"/>
	<task:scheduler id="scheduler" pool-size="10"/>

SpringBoot项目

官网给出简单的例子
具体的任务类

@Component
public class ScheduleTask {

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

Application:

@SpringBootApplication
@EnableScheduling  // 在spring boot的入口类Application.java中,允许支持schedule
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }
    
}

结果
在这里插入图片描述

@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 "";
}

案例

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秒执行一次");
    }
}

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  每个月的第三个星期,星期天 执行,#号只能出现在星期的位置

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

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分触发(光棍节)

猜你喜欢

转载自blog.csdn.net/qidasheng2012/article/details/84386662