Spring定时任务的使用

Spring定时任务的使用

实现定时任务简单的有四种方式:Timer\ScheduledThreadPool线程池\quartz(常用),以及springtask。

spring schedule比spring-quartz容易上手,之后我们对比下使用区别,于是简单的研究一下springtask的使用,并且运用到自己的项目中。其也有两种配置方式,第一种是基于xml配置,第二种是基于注解。

spring schedule不需要单独引用jar包,是spring-context依赖下的一个包org.springframework.scheduling中。所以引入spring的核心包此功能即可使用。

在实际的项目中,我们经常将job作为action层,在job中注入service去操作底层的dao,或者定时的向其他系统拉取数据,再或者向其他系统推送数据。

实际情况,我们使用spring schedule进行拉取收入费用信息动态更新预算,使用定时任务跑每个月的报销分摊数据,定时生成报销凭证并推送到财务系统

查看@Scheduled的源码:(位于spring-context包内)

package org.springframework.scheduling.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scheduled {

    /**
     * A cron-like expression, extending the usual UN*X definition to include
     * triggers on the second as well as minute, hour, day of month, month
     * and day of week.  e.g. {@code "0 * * * * MON-FRI"} means once per minute on
     * weekdays (at the top of the minute - the 0th second).
     * @return an expression that can be parsed to a cron schedule
     * @see org.springframework.scheduling.support.CronSequenceGenerator
     */
    String cron() default "";

    /**
     * Execute the annotated method with a fixed period between the end
     * of the last invocation and the start of the next.
     * @return the delay in milliseconds
     */
    long fixedDelay() default -1;

    /**
     * Execute the annotated method with a fixed period between invocations.
     * @return the period in milliseconds
     */
    long fixedRate() default -1;

    /**
     * Number of milliseconds to delay before the first execution of a
     * {@link #fixedRate()} or {@link #fixedDelay()} task.
     * @return the initial delay in milliseconds
     * @since 3.2
     */
    long initialDelay() default 0;

}

参数解释:(其实源码的注释也写的非常清楚了)

cron:cron表达式

fixedDelay:表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒

fixedRate:从上一个任务开始到下一个任务开始的间隔,单位是毫秒。

initialDelay:任务第一次被调用前的延时,单位毫秒。

需要注意的是上面的前三个属性只能保留一个,不能同时出现,最后一个延时操作可以与上面三个参数搭配

spring schedule的定时任务默认是单线程的处理方式是等待上一个任务执行完成后,再去执行下一个任务。(无论是cron还是fixedDelay、fixedRate都遵循这个原则)。下面举一些例子

接下来我们测试上面的参数: 

cron表达式
该参数接收一个cron表达式,cron表达式是一个字符串,字符串以5或6个空格隔开,分开共6或7个域,每一个域代表一个含义。

cron表达式语法

[秒] [分] [小时] [日] [月] [周] [年]
1
注:[年]不是必须的域,可以省略[年],则一共6个域

通配符说明:

* 表示所有值。 例如:在分的字段上设置 *,表示每一分钟都会触发。

? 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为”?” 具体设置为 0 0 0 10 * ?

- 表示区间。例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。

, 表示指定多个值,例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触发

/ 用于递增触发。如在秒上面设置”5/15” 表示从5秒开始,每增15秒触发(5,20,35,50)。 在日字段上设置’1/3’所示每月1号开始,每隔三天触发一次。

L 表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年[leap]), 在周字段上表示星期六,相当于”7”或”SAT”。如果在”L”前加上数字,则表示该数据的最后一个。例如在周字段上设置”6L”这样的格式,则表示“本月最后一个星期五”

W 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上置”15W”,表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 “1W”,它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,”W”前只能设置具体的数字,不允许区间”-“)。

# 序号(表示每月的第几个周几),例如在周字段上设置”6#3”表示在每月的第三个周六.注意如果指定”#5”,正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了) ;小提示:’L’和 ‘W’可以一组合使用。如果在日字段上设置”LW”,则表示在本月的最后一个工作日触发;周字段的设置,若使用英文字母是不区分大小写的,即MON与mon相同。

示例

每隔5秒执行一次:*/5 * * * * ?

每隔1分钟执行一次:0 */1 * * * ?

每天23点执行一次:0 0 23 * * ?

每天凌晨1点执行一次:0 0 1 * * ?

每月1号凌晨1点执行一次:0 0 1 1 * ?

每月最后一天23点执行一次:0 0 23 L * ?

每周星期六凌晨1点实行一次:0 0 1 ? * L

在26分、29分、33分执行一次:0 26,29,33 * * * ?

每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?

cron表达式使用占位符

另外,cron属性接收的cron表达式支持占位符。eg:

 

@EnableScheduling //开启缓存
@ComponentScan("com.scheduletest") //扫描component
@SpringBootApplication
public class WebApplication  {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}
package com.scheduletest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduleCronJob {
    private static final Logger log = LoggerFactory.getLogger(ScheduleCronJob.class);
    private static int count;

    @Scheduled(cron = "0/5 * * * * ?")
    public void cron() {
        log.info(Thread.currentThread().getName()+"===task run");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            log.error("InterruptedException ", e);
        }
        log.info(Thread.currentThread().getName()+"===task end", count++);
    }
}

2021-03-15 11:02:28.176  INFO 83762 --- [   scheduling-1] com.scheduletest.ScheduleCronJob         : scheduling-1===cron task run times 0 
2021-03-15 11:02:36.175  INFO 83762 --- [   scheduling-1] com.scheduletest.ScheduleCronJob         : scheduling-1===cron task run times 1 
2021-03-15 11:02:40.182  INFO 83762 --- [   scheduling-1] com.scheduletest.ScheduleCronJob         : scheduling-1===cron task run times 2 
2021-03-15 11:02:46.176  INFO 83762 --- [   scheduling-1] com.scheduletest.ScheduleCronJob         : scheduling-1===cron task run times 3 

2、fixedDelay :方法中模拟处理用了2s

package com.scheduletest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class FirstAnnotationJob {
    private static final Logger log = LoggerFactory.getLogger(FirstAnnotationJob.class);
    private static int count;

    @Scheduled(fixedDelay = 10000)
    public void cron() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            log.error("InterruptedException ", e);
        }
        log.info("spring anno task execute times {}", count++);
    }
}

结果:(实际每两次任务中间相差12s,也就是第一次任务结束10s后开启下次任务)

2021-03-15 11:02:26.172  INFO 83762 --- [   scheduling-1] com.scheduletest.FixedDelayJob           : scheduling-1===fixedDelay task run times 0 
2021-03-15 11:02:38.179  INFO 83762 --- [   scheduling-1] com.scheduletest.FixedDelayJob           : scheduling-1===fixedDelay task run times 1 
2021-03-15 11:02:52.008  INFO 83762 --- [   scheduling-1] com.scheduletest.FixedDelayJob           : scheduling-1===fixedDelay task run times 2 
2021-03-15 11:03:04.015  INFO 83762 --- [   scheduling-1] com.scheduletest.FixedDelayJob           : scheduling-1===fixedDelay task run times 3 

fixedRate测试:

package com.scheduletest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class FirstAnnotationJob {
    private static final Logger log = LoggerFactory.getLogger(FirstAnnotationJob.class);
    private static int count;

    @Scheduled(fixedRate = 10000)
    public void cron() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            log.error("InterruptedException ", e);
        }
        log.info("spring anno task execute times {}", count++);
    }
}

结果:(每两次任务相差10s,也就是本次任务开始之后10s后就开启下次任务,不管中间处理花费多长时间)

2021-03-15 11:02:24.167  INFO 83762 --- [   scheduling-1] com.scheduletest.FixedRateJob            : scheduling-1===fixedRate task run times 0 

2021-03-15 11:02:34.171  INFO 83762 --- [   scheduling-1] com.scheduletest.FixedRateJob            : scheduling-1===fixedRate task run times 1 
2021-03-15 11:02:44.171  INFO 83762 --- [   scheduling-1] com.scheduletest.FixedRateJob            : scheduling-1===fixedRate task run times 2 
2021-03-15 11:02:54.172  INFO 83762 --- [   scheduling-1] com.scheduletest.FixedRateJob            : scheduling-1===fixedRate task run times 3 
 附一个在线cron表达式生成器:http://cron.qqe2.com/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值