Spring Task定时任务

Spring Task定时任务

使用Scheduled注解来实现


看看Scheduled的源码

@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface Scheduled  
{  
  public abstract String cron();  

  public abstract long fixedDelay();  

  public abstract long fixedRate();  
}  

可以看出该注解有三个方法或者叫参数,分别表示的意思是:
cron:指定cron表达式
fixedDelay:官方文档解释:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。
fixedRate:官方文档解释:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。


用法如下

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component("taskJob")
public class TaskJob {

    //定时任务  每天早上3点执行一次
    @Scheduled(cron = "0 0 03 ? * *")
    public void job1() {  
        System.out.println("任务进行中。。。03:00分执行一次");
    } 

    //定时任务  每天15:13点执行一次
    @Scheduled(cron = "0 13 15 ? * *")
    public void job2() {  
        System.out.println("任务进行中。。。15:13执行一次");
    }

    @Scheduled(fixedDelay = 3000)
    public void job3() {  
        System.out.println("任务执行");
    } 

    @Scheduled(fixedRate = 30000)
    public void job4() {  
        System.out.println("任务执行");
    }
}

然后在spring-mvc.xml中配置,在头部的beans中添加

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.0.xsd"

<!--spring扫描注解的配置   -->
    <context:component-scan base-package="TaskJob的包名" /> 

    <!-- 开启这个配置,spring才能识别@Scheduled注解   -->  
    <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  
    <task:scheduler id="qbScheduler" pool-size="10"/>

这样,当你项目启动之后即可开始执行上面的任务

CRON表达式 含义
“0 0 12 * * ?” 每天中午十二点触发
“0 15 10 ? * *” 每天早上10:15触发
“0 15 10 * * ?” 每天早上10:15触发
“0 15 10 * * ? *” 每天早上10:15触发
“0 15 10 * * ? 2005” 2005年的每天早上10:15触发
“0 * 14 * * ?” 每天从下午2点开始到2点59分每分钟一次触发
“0 0/5 14 * * ?” 每天从下午2点开始到2:55分结束每5分钟一次触发
“0 0/5 14,18 * * ?” 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
“0 0-5 14 * * ?” 每天14:00至14:05每分钟一次触发
“0 10,44 14 ? 3 WED” 三月的每周三的14:10和14:44触发
“0 15 10 ? * MON-FRI” 每个周一、周二、周三、周四、周五的10:15触发

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值