springboot定时任务:@Scheduled

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/imHanweihu/article/details/81772713

1. 开启定时任务

项目启动类上加注解:@EnableScheduling,添加注解后SpringBoot认为我们要使用定时任务来完成一些业务逻辑了,内部会配置定时任务的配置文件,这个无需传统spring项目一样由我们配置。

package com.han.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

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

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

2. 配置线程池

新建class,线程池配置类ThreadAsyncConfigurer

package com.han.boot.config;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync // 开启对异步任务的支持
public class ThreadAsyncConfigurer implements AsyncConfigurer {
	@Bean
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
		// 设置核心线程数
		threadPool.setCorePoolSize(10);
		// 设置最大线程数
		threadPool.setMaxPoolSize(100);
		// 线程池所使用的缓冲队列
		threadPool.setQueueCapacity(10);
		// 等待任务在关机时完成--表明等待所有线程执行完
		threadPool.setWaitForTasksToCompleteOnShutdown(true);
		// 等待时间 (默认为0,此时立即停止),并没等待xx秒后强制停止
		threadPool.setAwaitTerminationSeconds(60);
		// 线程名称前缀
		threadPool.setThreadNamePrefix("MyAsync-");
		// 初始化线程
		threadPool.initialize();
		return threadPool;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return null;
	}
}

3. 应用定时任务

在你需要定时任务的方法上,加注解@Scheduled

@Scheduled(cron="0/5 * * * * *") // 每过5秒执行一次
public void test() {
    log.info("------");
}

cron表达式:参考https://www.cnblogs.com/xiandedanteng/p/3678650.html

猜你喜欢

转载自blog.csdn.net/imHanweihu/article/details/81772713