一、在spring配置文件中加入定时任务的相关配置:
1.beans标签中添加: xmlns:task="http://www.springframework.org/schema/task" http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd"
2.xml文本中加入:
<task:executor id="executor" pool-size="10"/> <task:scheduler id="scheduler" pool-size="10"/>
<task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>
二、在定时任务方法上使用@Scheduled注解即可:
//每天凌晨两点执行
@PostConstruct
@Scheduled(cron = "0 0 2 * * ?")
public void test() {
System.out.println("任务运行。。");
}
其中@PostConstruct注解修饰的方法在项目启动后先自动执行一次,随后会按定时设定的时间点执行。如果不需要在项目启动后执行,则可以去掉该注解。
附两个常用的定时cron:
//每天17点56执行一次 @Scheduled(cron = "0 56 17 * * ?") //每隔5秒执行一次 @Scheduled(cron = "0/5 * * * * ?")