一、定时任务作用?

定时任务相当于闹钟

在什么时间做什么事情(执行什么命令/脚本)


参数:

@EnableScheduling 开启对定时任务的支持

其中Scheduled注解中有以下几个参数:

  1.cron是设置定时执行的表达式,如 0 0/5 * * * ?每隔五分钟执行一次 秒 分 时 天 月

  2.zone表示执行时间的时区

  3.fixedDelay 和fixedDelayString 表示一个固定延迟时间执行,上个任务完成后,延迟多长时间执行

  4.fixedRate 和fixedRateString表示一个固定频率执行,上个任务开始后,多长时间后开始执行

  5.initialDelay 和initialDelayString表示一个初始延迟时间,第一次被调用前延迟的时间

二、举例说明

1、pom.xml中导入必要的依赖:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>

<dependencies>
<!-- SpringBoot 核心组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

2、写一个springboot的启动类:


启动类里面使用@EnableScheduling 注解开启功能,自动扫描


@SpringBootApplication
@EnableScheduling //开启定时任务
public class MainApplication {

public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}

3、新建一个Job类:



  • 要在任务的类上写@Component
  • 要在任务方法上写@Scheduled


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

import java.util.Date;

/**
* @ClassName Jobs
* @Author jeffrey
* @Description Jobs
**/

@Component
public class Jobs {
//表示方法执行完成后5秒
@Scheduled(fixedDelay = 5000)
public void fixedDelayJob() throws InterruptedException {
System.out.println("fixedDelay 每隔5秒" + new Date());
}

//表示每隔3秒
@Scheduled(fixedRate = 3000)
public void fixedRateJob() {

System.out.println("fixedRate 每隔3秒" + new Date());
}

//表示每天8时30分0秒执行
@Scheduled(cron = "0 0,30 0,8 ? * ? ")
public void cronJob() {
System.out.println(new Date() + " ...>>cron....");
}
}

执行结果如下:

fixedRate 每隔3秒Thu Jun 20 20:26:41 CST 2019
fixedDelay 每隔5秒Thu Jun 20 20:26:43 CST 2019
fixedRate 每隔3秒Thu Jun 20 20:26:44 CST 2019
fixedDelay 每隔5秒Thu Jun 20 20:26:48 CST 2019

三、总结



  • fixedDelay和fixedRate,单位是毫秒,这里这里就是5秒和3秒,它们的区别就是:fixedRate就是每多次分钟一次,不论你业务执行花费了多少时间。我都是1分钟执行1次,而fixedDelay是当任务执行完毕后1分钟在执行。所以根据实际业务不同,我们会选择不同的方式。
  • cron表达式:比如你要设置每天什么时候执行,就可以用它
    cron表达式,有专门的语法,而且感觉有点绕人,不过简单来说,大家记住一些常用的用法即可,特殊的语法可以单独去查。
    cron一共有7位,但是最后一位是年,可以留空,所以我们可以写6位:


* 第一位,表示秒,取值0-59
* 第二位,表示分,取值0-59
* 第三位,表示小时,取值0-23
* 第四位,日期天/日,取值1-31
* 第五位,日期月份,取值1-12
* 第六位,星期,取值1-7,星期一,星期二...,注:不是第1周,第二周的意思
另外:1表示星期天,2表示星期一。
* 第7为,年份,可以留空,取值1970-2099


cron中,还有一些特殊的符号,含义如下:


(*)星号:可以理解为每的意思,每秒,每分,每天,每月,每年...
(?)问号:问号只能出现在日期和星期这两个位置。
(-)减号:表达一个范围,如在小时字段中使用“10-12”,则表示从10到12点,即10,11,12
(,)逗号:表达一个列表值,如在星期字段中使用“1,2,4”,则表示星期一,星期二,星期四
(/)斜杠:如:x/y,x是开始值,y是步长,比如在第一位(秒) 0/15就是,从0秒开始,每15秒,最后就是0,15,30,45,60 另:*/y,等同于0/y


下面列举几个例子供大家来验证:


0 0 3 * * ?     每天3点执行
0 5 3 * * ? 每天3点5分执行
0 5 3 ? * * 每天3点5分执行,与上面作用相同
0 5/10 3 * * ? 每天3点的 5分,15分,25分,35分,45分,55分这几个时间点执行
0 10 3 ? * 1 每周星期天,3点10分 执行,注:1表示星期天
0 10 3 ? * 1#3 每个月的第三个星期,星期天 执行,#号只能出现在星期的位置