基於@Scheduled註解的Spring定時任務

一、建立spring-task.xml

在xml文件中加入命名空間css

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
          http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd">
</beans>

啓用註解驅動java

<task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true" />

配置線程池,若不配置多任務下會有問題web

<task:scheduler id="scheduler" pool-size="10" />

spring-task.xmlredis

<?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:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
          http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd">

    <!-- 以下實現是經過線程池執行的 -->
    <task:executor id="executor" pool-size="10" />
    <task:scheduler id="scheduler" pool-size="10" />

    <!-- 支持以@Scheduled註解的方式任務調度 -->
    <task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true" />

</beans>
View Code

二、在spring.xml中import上面的spring-task.xml文件

<?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"
       xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    <context:property-placeholder
            location="
            classpath*:resources.properties,
            classpath*:datasource.properties,
            classpath*:redis.properties,
            classpath*:mongodb.properties,
            classpath*:esb.properties,
            classpath*:cas.properties"/>

    <!-- 掃描註解Bean -->
    <context:component-scan
            base-package="com.ylzinfo.**.service,com.ylzinfo.**.task,com.ylzinfo.**.extra,com.ylzinfo.esscard.**.config">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation"
                                expression="org.springframework.web.bind.annotation.RestController"/>
        <context:exclude-filter type="annotation"
                                expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>
    <!-- 開啓AOP監聽 只對當前配置文件有效 -->
    <aop:aspectj-autoproxy expose-proxy="true"/>

    <import resource="spring-mybatis.xml"/>
    <import resource="spring-validator.xml"/>
    <!--<import resource="spring-cache-ehcache.xml"/>-->
    <import resource="spring-cache-redis.xml"/>
    <import resource="spring-task.xml"/>
    <import resource="spring-shiro.xml"/>
    <!--<import resource="spring-axis2.xml" />-->
    <!--<import resource="spring-shiro-cas.xml"/> -->
    <import resource="spring-esb.xml"/>
    <!-- <import resource="spring-shiro-kisso.xml"/> -->
    <!-- <import resource="spring-fs.xml"/> <import resource="spring-mongodb.xml"/>
        <import resource="spring-logback.xml"/> -->

    <!-- 國際化的消息資源文件(本系統中主要用於顯示/錯誤消息定製) -->
    <bean id="messageSource"
          class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <!-- 在web環境中必定要定位到classpath 不然默認到當前web應用下找 [classpath:messages_zh_CN,
                    classpath:messages_zh, classpath:messages] -->
                <value>classpath:messages/messages</value>
                <value>classpath:messages/ValidationMessages</value>
            </list>
        </property>
        <!-- useCodeAsDefaultMessage默認爲false,這樣當Spring在ResourceBundle中找不到messageKey的話,
            就拋出NoSuchMessageException,把它設置爲True,則找不到不會拋出異常 -->
        <property name="useCodeAsDefaultMessage" value="false"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="cacheSeconds" value="60"/>
    </bean>

    <!-- spring工具類 方便在非spring管理環境中獲取bean -->
    <bean class="com.eva.core.util.SpringUtils"/>
 
</beans>
View Code

三、實現定時任務

public interface ScheduledService {
    public void test();
}
import com.esscard.extra.task.ScheduledService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;


@Component
public class ScheduledImpl implements ScheduledService {
    private Logger logger = LoggerFactory.getLogger(ScheduledImpl.class);

    @Scheduled(cron="0/5 * *  * * ? ")
    @Override
    public void test() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println(df);
        logger.info("時間:" + df.format(new Date()));
    }
}

四、測試結果

五、@Scheduled解析

1. cron

該參數接收一個cron表達式cron表達式是一個字符串,字符串以5或6個空格隔開,分開共6或7個域,每個域表明一個含義。spring

cron表達式語法
[秒] [分] [小時] [日] [月] [周] [年]

注:[年]不是必須的域,能夠省略[年],則一共6個域mongodb

序號 說明 必填 容許填寫的值 容許的通配符
1 0-59 , - * /
2 0-59 , - * /
3 0-23 , - * /
4 1-31 , - * ? / L W
5 1-12 / JAN-DEC , - * /
6 1-7 or SUN-SAT , - * ? / L #
7 1970-2099 , - * /

通配符說明:

  • * 表示全部值。 例如:在分的字段上設置 *,表示每一分鐘都會觸發。
  • ? 表示不指定值。使用的場景爲不須要關心當前設置這個字段的值。例如:要在每個月的10號觸發一個操做,但不關心是周幾,因此須要周位置的那個字段設置爲」?」 具體設置爲 0 0 0 10 * ?
  • - 表示區間。例如 在小時上設置 「10-12」,表示 10,11,12點都會觸發。
  • , 表示指定多個值,例如在周字段上設置 「MON,WED,FRI」 表示週一,週三和週五觸發
  • / 用於遞增觸發。如在秒上面設置」5/15」 表示從5秒開始,每增15秒觸發(5,20,35,50)。 在月字段上設置’1/3’所示每個月1號開始,每隔三天觸發一次。
  • L 表示最後的意思。在日字段設置上,表示當月的最後一天(依據當前月份,若是是二月還會依據是不是潤年[leap]), 在周字段上表示星期六,至關於」7」或」SAT」。若是在」L」前加上數字,則表示該數據的最後一個。例如在周字段上設置」6L」這樣的格式,則表示「本月最後一個星期五」
  • W 表示離指定日期的最近那個工做日(週一至週五). 例如在日字段上置」15W」,表示離每個月15號最近的那個工做日觸發。若是15號正好是週六,則找最近的週五(14號)觸發, 若是15號是周未,則找最近的下週一(16號)觸發.若是15號正好在工做日(週一至週五),則就在該天觸發。若是指定格式爲 「1W」,它則表示每個月1號日後最近的工做日觸發。若是1號正是週六,則將在3號下週一觸發。(注,」W」前只能設置具體的數字,不容許區間」-「)。
  • # 序號(表示每個月的第幾個周幾),例如在周字段上設置」6#3」表示在每個月的第三個週六.注意若是指定」#5」,正好第五週沒有周六,則不會觸發該配置(用在母親節和父親節再合適不過了) ;小提示:’L’和 ‘W’能夠一組合使用。若是在日字段上設置」LW」,則表示在本月的最後一個工做日觸發;周字段的設置,若使用英文字母是不區分大小寫的,即MON與mon相同。

示例

每隔5秒執行一次:*/5 * * * * ?express

每隔1分鐘執行一次:0 */1 * * * ?json

天天23點執行一次:0 0 23 * * ?服務器

天天凌晨1點執行一次:0 0 1 * * ?mybatis

每個月1號凌晨1點執行一次:0 0 1 1 * ?

每個月最後一天23點執行一次:0 0 23 L * ?

每週星期天凌晨1點實行一次:0 0 1 ? * L

在26分、29分、33分執行一次:0 26,29,33 * * * ?

天天的0點、13點、18點、21點都執行一次:0 0 0,13,18,21 * * ?

1.cron

2. zone

時區,接收一個java.util.TimeZone#IDcron表達式會基於該時區解析。默認是一個空字符串,即取服務器所在地的時區。好比咱們通常使用的時區Asia/Shanghai。該字段咱們通常留空。

3. fixedDelay

上一次執行完畢時間點以後多長時間再執行。如:

@Scheduled(fixedDelay = 5000) //上一次執行完畢時間點以後5秒再執行

4. fixedDelayString

3. fixedDelay 意思相同,只是使用字符串的形式。惟一不一樣的是支持佔位符。如:

@Scheduled(fixedDelayString = "5000") //上一次執行完畢時間點以後5秒再執行

 

5. fixedRate

上一次開始執行時間點以後多長時間再執行。如:

@Scheduled(fixedRate = 5000) //上一次開始執行時間點以後5秒再執行

6. fixedRateString

5. fixedRate 意思相同,只是使用字符串的形式。惟一不一樣的是支持佔位符。

7. initialDelay

第一次延遲多長時間後再執行。如:

@Scheduled(initialDelay=1000, fixedRate=5000) //第一次延遲1秒後執行,以後按fixedRate的規則每5秒執行一次

8. initialDelayString

7. initialDelay 意思相同,只是使用字符串的形式。惟一不一樣的是支持佔位符。

相關文章
相關標籤/搜索