本文爲博主原創,未經容許不得轉載spring
項目中要常常事項定時功能,在網上學習了下用spring的定時功能,基本有兩種方式,在這裏進行簡單的總結,ide
以供後續參考,此篇只作簡單的應用。學習
1.在spring-servlet.xml文件中加入task的命名空間:spa
xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"
而後使用task配置掃描註解code
<!-- 定時任務 --> <task:annotation-driven scheduler="qbScheduler" mode="proxy"/> <task:scheduler id="qbScheduler" />
此時就能夠直接使用@Scheduled(cron = "時間格式串"),應用該註解就能夠實現定時的功能xml
@Scheduled(cron = "0/5 * * * * ?") //每隔5秒執行一次定時任務 public void consoleInfo(){ System.out.println("定時任務"); }
第二種方法爲:不使用註解實現定時任務,將定時的功能在spring配置文件中實現。blog
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」
<description> 定時任務 </description>
//定時註解驅動 <task:annotation-driven /> //進行定時任務的類,將其定義爲一個bean <bean id="spaceStatisticsService" class="com.pojo.system.manager.sigar.impl.SpaceStatisticsServiceImpl"></bean>
//經過task標籤,定義定時功能 <task:scheduled-tasks> <task:scheduled ref="spaceStatisticsService" method="statisticSpace" cron="59 59 23 * * ?" /> </task:scheduled-tasks>
要實現的代碼部分爲:ip
@Service public class SpaceStatisticsServiceImpl implements SpaceStatisticsService { @Override public void statisticSpace() { System.out.println("實現定時功能"); } }
總結:兩種方法都能實現定時的功能,但明顯第一種方式會比較簡潔,並且更加方便。servlet