SSM整合SpringTask定时任务基于注解的使用

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

  

 

原文地址:https://www.cnblogs.com/Amywangqing/p/13795357.html