使用轻量级Spring @Scheduled注解执行定时任务
标签:
WEB项目中需要加入一个定时执行任务,可以使用Quartz来实现,由于项目就一个定时任务,所以想简单点,不用去配置那些Quartz的配置文件,所以就采用了Spring @Scheduled注解来实现了定时任务。在这里做个备注。
spring配置文件 xmlns中加入一段:
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注解:
<task:annotation-driven/> <context:annotation-config/> <context:component-scan base-package="com.xx.xx"/>
编写JAVA代码:
@Component public class ScheduledTaskManager { /** * cron表达式:* * * * * *(共6位,使用空格隔开,具体如下) * cron表达式:*(秒0-59) *(分钟0-59) *(小时0-23) *(日期1-31) *(月份1-12或是JAN-DEC) *(星期1-7或是SUN-SAT) */ /** * 定时卡点计算。每天凌晨 02:00 执行一次 */ @Scheduled(cron = "0 0 2 * * *") public void autoCardCalculate() { System.out.println("定时卡点计算... " + new Date()); } /** * 心跳更新。启动时执行一次,之后每隔1分钟执行一次 */ @Scheduled(fixedRate = 1000*60*1) public void heartbeat() { System.out.println("心跳更新... " + new Date()); } }
使用轻量级Spring @Scheduled注解执行定时任务
标签:
WEB项目中需要加入一个定时执行任务,可以使用Quartz来实现,由于项目就一个定时任务,所以想简单点,不用去配置那些Quartz的配置文件,所以就采用了Spring @Scheduled注解来实现了定时任务。在这里做个备注。
spring配置文件 xmlns中加入一段:
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注解:
<task:annotation-driven/> <context:annotation-config/> <context:component-scan base-package="com.xx.xx"/>
编写JAVA代码:
@Component public class ScheduledTaskManager { /** * cron表达式:* * * * * *(共6位,使用空格隔开,具体如下) * cron表达式:*(秒0-59) *(分钟0-59) *(小时0-23) *(日期1-31) *(月份1-12或是JAN-DEC) *(星期1-7或是SUN-SAT) */ /** * 定时卡点计算。每天凌晨 02:00 执行一次 */ @Scheduled(cron = "0 0 2 * * *") public void autoCardCalculate() { System.out.println("定时卡点计算... " + new Date()); } /** * 心跳更新。启动时执行一次,之后每隔1分钟执行一次 */ @Scheduled(fixedRate = 1000*60*1) public void heartbeat() { System.out.println("心跳更新... " + new Date()); } }
@Scheduled有两种方式:cron表达式和fixedRate
两种都可以定时每隔一段时间执行,个人觉得两种方式区别是fixedTate方式是应用启动时候会先执行一次,cron表达式能配置更加复杂的情况。