spring mvc 使用注解执行定时任务
1.application配置文件加上
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.1.xsd"
<!-- 默认的定时任务注解映射支持 -->
<task:annotation-driven />
2.
package com.wboss.web.scheduled;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 邮件发送定时器
* @author Wang Zhen
*
*/
@Component
public class SingleMailScheduled {
@Scheduled(cron="0/5 * * * * ?") //每5秒执行一次
public void exec() {
System.out.println("发送邮件成功!");
}
}
注:spring 在使用scheduled注解定时任务时,当application.xml中配置 default-lazy-init="true"时将不会执行定时任务,必须设置为false或去掉default-lazy-init,当然默认为false.