Spring自带实现定时任务有两种方式,一种是通过注解的方式实现,一种是通过在配置文件中配置后实现。
一、通过spring的注解( @Scheduled)
1.task命名空间:
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"
2.xml文件中配置:
<task:annotation-driven />
<task:scheduler pool-size="50" id="threadPoolTaskScheduler"/>
<task:executor id="executor" pool-size="200"/>
或直接使用注解:
@EnableScheduling
public class UpdateConfigTask {
}
3.编写定时任务类和方法,方法使用@Scheduled注解:
@Component
public class UpdateConfigTask {
@Scheduled(cron = "0/5 * * * * ?")
public void updateConfig() {
System.out.println("hello");
}
}
二、通过spring的配置文件:
<task:scheduled-tasks scheduler="threadPoolTaskScheduler">
<task:scheduled ref="updateConfigTask" method="updateConfig" cron="0/5 * * * * ?"/>
</task:scheduled-tasks>
<task:scheduler pool-size="50" id="threadPoolTaskScheduler"/>
cron表达式解析工具:
http://cron.qqe2.com/