使用轻量级Spring @Scheduled注解执行定时任务

使用轻量级Spring @Scheduled注解执行定时任务

时间: 2016-10-19 17:11:36      阅读: 657      评论: 0      收藏: 0      [点我收藏+]

标签:

     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注解执行定时任务

时间: 2016-10-19 17:11:36      阅读: 657      评论: 0      收藏: 0      [点我收藏+]

标签:

     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表达式能配置更加复杂的情况。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值