一个简单的基于spring mvc的定时器
所需最少jar
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!--Spring ApplicationContext 载入 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Spring ApplicationContext配置文件的路径*,可使用通配符,多个路径用*号分隔
此参数用于后面的Spring-Context loader -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/timer/config/applicationContext.xml</param-value>
</context-param>
</web-app>
applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
default-autowire="byName" default-lazy-init="false">
<!-- 定时器开关-->
<task:annotation-driven />
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.timer" />
</beans>
定时器类:
package com.timer.controller;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TimerController {
/**
* 每天凌晨清空所有用户分享数据
*/
@Scheduled(cron = "0 53 17 * * ?")
public void clearCustomerShare(){
System.out.println("========================sys");
}
}
//==========================cron表达式:http://rainbowdesert.iteye.com/blog/2107220
由6-7个组成
秒-分-时 天-月-日-年 用空格分开