Spring版本5.1.五、JDK版本1.8
首先有一個定時的任務類java
package com.yuanweiquan.learn.quartzs; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyQuartzs { @Scheduled(cron = "*/5 * * * * ?")//每五秒執行一次 public void quartzs() { System.out.println(LocalDateTime.now().toString()); } }
XML配置spring
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> //掃描包路勁 <context:component-scan base-package="com.yuanweiquan.learn.*"></context:component-scan> //啓用定時任務 <task:annotation-driven></task:annotation-driven> </beans>
啓動Spring容器,控制檯打印結果以下:code
2019-03-29T15:15:30.011 2019-03-29T15:15:35.002 2019-03-29T15:15:40.001 2019-03-29T15:15:45.001 2019-03-29T15:15:50.001
5秒鐘打印一次,恰好符合咱們的需求。
可是若是咱們的任務執行時間大於任務間隔時間5s,會怎麼樣呢?咱們打印後設置一個休眠時間component
public class MyQuartzs { @Scheduled(cron = "*/5 * * * * ?") public void quartzs() { System.out.println(LocalDateTime.now().toString()); try { Thread.sleep(6000); } catch (Exception e) { e.printStackTrace(); } } }
再次啓動spring容器,控制檯打印結果以下:xml
2019-03-29T15:18:45.011 2019-03-29T15:18:55.001 2019-03-29T15:19:05.001
從打印結果能夠看出來,任務10s執行了一次,而不是咱們但願的5s。
緣由是當定時任務準備執行時,發現上次任務還未執行完,就會再次等待休眠時間,再次執行,直到任務能夠執行爲止。io