Spring之定时任务注解@Scheduled详解
									
下文笔者讲述@Scheduled注解的详细使用示例分享,如下所示
				 
				定时任务简介
定时任务就是在指定时间运行一个任务 
    或轮询运行一个任务
定时任务实现思路
JDK的Timer Spring提供的轻量级的Scheduled Task QuartZ和Linux Cron等下面笔者将着重介绍@Scheduled注解的实现方法
@Scheduled注解使用注意事项: 1.@Scheduled注解应用在没有返回类型及没有参数的方法上 2.Spring中开启@Scheduled注解,只需使用@EnableScheduling注解即可 3.SpringBoot中,只需在启动类上加上@EnableScheduling注解即可
开启Scheduled的示例
@Configuration
@EnableScheduling
public class SchedulingConfig {
}
固定延迟fixedDelay
指下一个任务的开始与上一个任务的结束间隔总是固定的时长
   而且总是会等上一个任务完成
   才会开启下一个任务
   如果需求是有这样依赖要求的
     使用这种模式是非常合适的
例
@Scheduled(fixedDelay = 1000)
public void fixedDelay() {
  log.info("fixedDelay");
}
参数为1000
 代表固定延迟为1000毫秒,即1秒钟 
固定频率fixedRate
定频任务的特性是任务的执行的时间间隔总是一样的
  如:
    每1小时执行一次
	 就是任务执行开始的时间点的时间间隔为1小时
例
@Scheduled(fixedRate = 2000)
public void fixedRate() {
  log.info("fixedRate");
}
参数为2000,则每2秒执行一次,输出为:
@Scheduled默认单线程
默认是单线程的,不会并行执行 固定频率 下一次的任务也必须等到上一次任务执行完毕才会开始例
@Scheduled(fixedRate = 1000)
public void fixedRateLongTimeTask() throws InterruptedException {
  log.info("fixedRateLongTimeTask");
  Thread.sleep(3000);
}
 
注解@Async实现@Scheduled多线程
 
@Async
@Scheduled(fixedRate = 1000)
public void fixedRateLongTimeTask() throws InterruptedException {
  log.info("fixedRateLongTimeTask");
  Thread.sleep(3000);
}
注意事项:
    SpringBoot在启动类上加上@EnableAsync即可
 
初始延迟initialDelay
初始延迟:
  指用initialDelay来指定
  它可以延迟第一次任务执行的时间
  
  如:
    例子的参数为30秒
     则在启动30秒后
     才开始执行第一次
     可以减轻项目启动的负担
     也可以为任务执行前准备数据。
@Scheduled(fixedDelay = 1000, initialDelay = 30*1000)
public void fixedDelayWithIntialDelay() {
  log.info("fixedDelayWithIntialDelay");
}
 
Cron表达式
@Scheduled(cron = "8 * * ? * *")
public void cron() {
  log.info("cron");
}
每8秒运行一次
 
参数配置化
 
@Scheduled(cron = "${test.cron}")
public void cronWithConfig() {
  log.info("cronWithConfig");
}
//application.properties 配置
test.cron=* * * ? * *
代码1秒执行一次
 									
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

 
			 
                
                
                
               
 
          

