`

spring @Scheduled注解执行定时任务

阅读更多
spring @Scheduled注解方式配置定时器


在sping配置文件中:
配置注解扫描:

<!-- 配置注解扫描 -->
<context:annotation-config/>
<context:component-scan base-package="demo.test" />

<!--配置sping定时器开关 -->
<task:annotation-driven/>

    <!-- Spring定时器注解开关(可以不添加) -->  
 
    <!-- 此处对于定时时间的配置会被注解中的时间配置覆盖,因此,以注解配置为准 -->  
    <task:scheduled-tasks scheduler="myScheduler">  
        <task:scheduled ref="scheduledTaskManager" method="autoCardCalculate" cron="1/5 * * * * *"/>  
    </task:scheduled-tasks>  
    <task:scheduler id="myScheduler" pool-size="10"/>  


执行任务的POJO类如下:

package com.demo.schedule;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
 * Created with IntelliJ IDEA.
 * Author: 
 * Date: 2013-10-09 14:39
 * Function: Spring定时任务管理
 */
@Component("scheduledTaskManager")
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());
    }

    /**
     * 卡点持久化。启动时执行一次,之后每隔2分钟执行一次
     */
    @Scheduled(fixedRate = 1000*60*2)
    public void persistRecord() {
        System.out.println("卡点持久化... " + new Date());
    }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics