前言
定時任務在我們工作中應用非常廣泛,在spring中定時任務實現可以用spring自己的Scheduled
實現,也可以使用第三方框架Quartz
來實現。 本文我們來看一下Scheduled
的實現方式,通過簡單的註解開啓定時任務支持即可。
配置@EnableScheduling註解
- 我們新增一個定時的配置類,配置線程池,可選擇配置拒絕策略。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableScheduling
public class SchedulerTaskConfig implements SchedulingConfigurer {
private static final Logger LOGGER = LoggerFactory.getLogger(SchedulerTaskConfig.class);
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.setScheduler(schedulerTheadPool());
}
/**
* 線程池
* <p>
* @code {@Bean(destroyMethod = "shutdown")}當線程執行完畢,自動關閉線程池
* </p>
* @return
*/
@Bean(destroyMethod = "shutdown")
public Executor schedulerTheadPool() {
// 核心線程數等於運行時可用線程
int coreSize = Runtime.getRuntime().availableProcessors();
return new ScheduledThreadPoolExecutor(coreSize, new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
// 給定時任務的線程設置名字
return new Thread(runnable, "scheduler-task");
}
}, new RejectedExecutionHandler() {
// 拒絕策略
@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) {
LOGGER.error("執行任務失敗 task : {}", runnable);
}
});
}
}
配置@Scheduled註解
@Scheduled
註解支持initialDelay
初始化延遲N毫秒執行,fixedDelay
每隔N毫秒執行一次
新增一個任務類,MyTask.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyTask {
private static final Logger LOGGER = LoggerFactory.getLogger(MyTask.class);
/**
* initialDelay - 初始化時延遲5秒執行
* fixedDelay - 每隔2秒執行一次
*/
@Scheduled(initialDelay = 5000,fixedDelay = 2000)
public void execute(){
LOGGER.info("==============執行定時任務 initialDelay & fixedDelay ==============");
}
}
- 同時也支持
cron
表達式來配置更細粒度的定時任務 。 新增任務類CornTask.java 配置Corn表達式
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class CornTask {
private static final Logger LOGGER = LoggerFactory.getLogger(CornTask.class);
/**
* 5 秒執行一次
*/
@Scheduled(cron = "0/5 * * * * *")
public void execute(){
LOGGER.info("==============執行定時任務 CornTask ==============");
}
}
啓動測試
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.1)
2020-12-17 10:11:14.256 INFO 65437 --- [ main] com.lb.springboot.Application : Starting Application using Java 1.8.0_211 on yunnashengdeMacBook-Pro.local with PID 65437 (/Users/yunnasheng/work/github-workspace/springboot-scheduler-task/target/classes started by yunnasheng in /Users/yunnasheng/work/github-workspace/springboot-quickstart-002)
2020-12-17 10:11:14.258 INFO 65437 --- [ main] com.lb.springboot.Application : No active profile set, falling back to default profiles: default
2020-12-17 10:11:14.945 INFO 65437 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8002 (http)
2020-12-17 10:11:14.951 INFO 65437 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-12-17 10:11:14.951 INFO 65437 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2020-12-17 10:11:14.984 INFO 65437 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/task] : Initializing Spring embedded WebApplicationContext
2020-12-17 10:11:14.984 INFO 65437 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 694 ms
2020-12-17 10:11:15.188 INFO 65437 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8002 (http) with context path '/task'
2020-12-17 10:11:15.200 INFO 65437 --- [ main] com.lb.springboot.Application : Started Application in 1.144 seconds (JVM running for 1.558)
2020-12-17 10:11:20.001 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.CornTask : ==============執行定時任務 CornTask ==============
2020-12-17 10:11:20.197 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:21.201 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:22.206 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:23.211 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:24.216 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:25.001 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.CornTask : ==============執行定時任務 CornTask ==============
2020-12-17 10:11:25.220 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:26.225 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:27.227 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:28.229 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:29.235 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:30.001 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.CornTask : ==============執行定時任務 CornTask ==============
2020-12-17 10:11:30.237 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:31.243 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:32.245 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:33.250 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:34.256 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:35.001 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.CornTask : ==============執行定時任務 CornTask ==============
2020-12-17 10:11:35.262 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:36.267 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:37.268 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:38.270 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
2020-12-17 10:11:39.271 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============執行定時任務 initialDelay & fixedDelay ==============
demo案例源碼:https://github.com/yunnasheng/springboot-scheduler-task.git