1.在入口程序出DemoApplication 添加注解@EnableScheduling,如下所示:

@SpringBootApplication
@EnableScheduling
public class DemoApplication {

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

2.@scheduled注解用来配置到方法上来完成对应的定时任务的配置,如执行时间,间隔时间,延迟时间等等,下面我们就来详细的看下对应的属性配置。
创建一个定时实体PrintTask
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Componenpublic
class PrintTask

fixedDelay配置了该属性后会等到方法执行完成后延迟配置的时间再次执行该方法,

initialDelay 该属性的作用是第一次执行延迟时间,只是做延迟的设定,并不会控制其他逻辑,所以要配合fixedDelay或者fixedRate来使用

   @Scheduled(initialDelay = 1000 * 10,fixedDelay = 1000 * 30)
public void fixedDelay()throws Exception
{

System.out.println("执行定时任务fixedDelay的时间"+ new Date(System.currentTimeMillis()));
}
}


fixedRate 上一个调用开始后再次调用的延时(不用等待上一次调用完成),这样就会存在重复执行的问题.
@Scheduled(fixedRate = 1000 * 1)
public void fixedRate() throws Exception
{
Thread.sleep(3000);
System.out.println("执行定时任务fixedRate的时间"+ new Date(System.currentTimeMillis()));
}

 

     cron 每天的17点18分执行。。(语法有点麻烦)

@Scheduled(cron="0 18 17 * * ?")
public void cronJob(){
System.out.println((new Date())+" >>cron执行....");
}

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

(*)星号:可以理解为每的意思,每秒,每分,每天,每月,每年...
(?)问号:问号只能出现在日期和星期这两个位置,表示这个位置的值不确定,每天3点执行,所以第六位星期的位置,
我们是不需要关注的,就是不确定的值。同时:日期和星期是两个相互排斥的元素,通过问号来表明不指定值。
比如,1月10日,比如是星期1,如果在星期的位置是另指定星期二,就前后冲突矛盾了。
(-)减号:表达一个范围,如在小时字段中使用“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