spring定时任务有两种实现,一个是在xml中配置bean,另一种就是注解,我肯定倾向注解,方便很多;
首先要在spring的配置文件中配置下:
<?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: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.xsd">
<!-- 启动定时器 -->
<task:annotation-driven/>
<task:scheduler id="scheduler" pool-size="5"/>
</beans>
你可以是自己建一个xml文件,我建的叫spring-task.xml,然后把这个xml文件引入到主的那个spring.xml文件中,方法如下,和类中引入包类似:
<import resource="spring-task.xml"/>
或者不引导主的xml中,那就直接引入到web.xml中,都可以:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:META-INF/spring/spring-task.xml,classpath*:META-INF/spring/spring*.xml</param-value>
</context-param>
配置完成后,建个定时任务的类:
/**
* Created by zelei.fan on 2016/11/11.
*/
@Component
public class ReportSend {
/**
* 定时发送报表
*/
@Scheduled(cron = "0/5 * * * * ?")//里面的叫cron表达式,表示周期,多久执行一次
public void sendReportMail(HttpSession session){
System.out.println("aaa");
}
}
我那个定义的是每5秒走一次这个方法,如果需要其他周期,可以百度下,cron表达式,自动生成;
这样就完成了,程序启动后就会按指定的周期运行了