SSM整合SpringTask定時任務基於註解的使用
阿新 • • 發佈:2020-10-10
1.重點是引入task的schema:
xmlns:task="http://www.springframework.org/schema/task" http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
2.註解使用必須在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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 啟動註解驅動的spring mvc 功能 --> <mvc:annotation-driven /> <!-- 啟動包掃描功能 --> <context:component-scan base-package="com.qingfeng.controller" /> <context:component-scan base-package="com.qingfeng.service" /> <!-- 開啟任務排程註解--> <task:annotation-driven ></task:annotation-driven>> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
3.SpringTaskJob定時類
package com.qingfeng.service; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component//把普通pojo例項化到spring容器中,相當於配置檔案中的<bean id="" class=""/> public class SpringTaskJob { @Scheduled(cron = "0/2 * * * * ?") public void cron() { System.out.println("執行定時任務,當前時間:"+System.currentTimeMillis()); } }
4.輸出結果
執行定時任務,當前時間:1602335496018 執行定時任務,當前時間:1602335498001 執行定時任務,當前時間:1602335500001 執行定時任務,當前時間:1602335502001 執行定時任務,當前時間:1602335504001 執行定時任務,當前時間:1602335506001 執行定時任務,當前時間:1602335508008