Spring版本5.1.5、JDK版本1.8首先有一个定时的任务类package com.yuanweiquan.learn.quartzs;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class MyQuartzs { @Scheduled(cron = “/5 * * * * ?”)//每五秒执行一次 public void quartzs() { System.out.println(LocalDateTime.now().toString()); }}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: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容器,控制台打印结果如下:2019-03-29T15:15:30.0112019-03-29T15:15:35.0022019-03-29T15:15:40.0012019-03-29T15:15:45.0012019-03-29T15:15:50.0015秒钟打印一次,刚好符合我们的需求。但是如果我们的任务执行时间大于任务间隔时间5s,会怎么样呢?我们打印后设置一个休眠时间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容器,控制台打印结果如下:2019-03-29T15:18:45.0112019-03-29T15:18:55.0012019-03-29T15:19:05.001从打印结果可以看出来,任务10s执行了一次,而不是我们希望的5s。原因是当定时任务准备执行时,发现上次任务还未执行完,就会再次等待休眠时间,再次执行,直到任务可以执行为止。