Spring Boot 实现定时任务的 4 种方式

使用Timer
这个目前在项目中用的较少,直接贴demo代码。具体的介绍可以查看api

public class TestTimer {

public static void main(String[] args) {

   TimerTask timerTask = new TimerTask() {
       @Override
       public void run() {
           System.out.println("task  run:"+ new Date());
       }

   };

   Timer timer = new Timer();

   //安排指定的任务在指定的时间开始进行重复的固定延迟执行。这里是每3秒执行一次
   timer.schedule(timerTask,10,3000);

}

}
使用ScheduledExecutorService
该方法跟Timer类似,直接看demo:

public class TestScheduledExecutorService {

public static void main(String[] args) {

   ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

   // 参数:1、任务体 2、首次执行的延时时间
   //      3、任务执行间隔 4、间隔时间单位
   service.scheduleAtFixedRate(()->System.out.println("task ScheduledExecutorService "+new Date()), 0, 3, TimeUnit.SECONDS);

}

}
使用Spring Task
简单的定时任务
在SpringBoot项目中,我们可以很优雅的使用注解来实现定时任务,首先创建项目,导入依赖:

org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test 创建任务类:

@Slf4j

@Component

public class ScheduledService {

@Scheduled(cron = “0/5 * * * * *”)
public void scheduled(){
log.info("=====>>>>>使用cron {}",System.currentTimeMillis());
}

@Scheduled(fixedRate = 5000)
public void scheduled1() {
log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis());
}

@Scheduled(fixedDelay = 5000)
public void scheduled2() {
log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis());
}

}
在主类上使用@EnableScheduling注解开启对定时任务的支持,然后启动项目

推荐:Spring快速开启计划。可以看到三个定时任务都已经执行,并且使同一个线程中串行执行,如果只有一个定时任务,这样做肯定没问题,当定时任务增多,如果一个任务卡死,会导致其他任务也无法执行。关注Java技术栈微信公众号,在后台回复关键字:spring,可以获取更多栈长整理的 Spring 系列技术干货。

多线程执行
在传统的Spring项目中,我们可以在xml配置文件添加task的配置,而在SpringBoot项目中一般使用config配置类的方式添加配置,所以新建一个AsyncConfig类。关注Java技术栈微信公众号,在后台回复关键字:spring,可以获取更多栈长整理的 Spring 系列技术干货。

@Configuration
@EnableAsync
public class AsyncConfig {

/*
 *此处成员变量应该使用@Value从配置中读取
*/

private int corePoolSize = 10;
private int maxPoolSize = 200;
private int queueCapacity = 10;

@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}

}
深圳网站建设www.sz886.com

你可能感兴趣的:(Spring Boot 实现定时任务的 4 种方式)