前言
定时任务在我们工作中应用非常广泛,在spring中定时任务实现可以用spring自己的 Scheduled
实现,也可以使用第三方框架 Quartz
来实现。 本文我们来看一下 Scheduled
的实现方式,通过简单的注解开启定时任务支持即可。
配置@EnableScheduling注解
- 我们新增一个定时的配置类,配置线程池,可选择配置拒绝策略。
* @code {@Bean(destroyMethod = "shutdown")}当线程执行完毕,自动关闭线程池* 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);@Overridepublic void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {scheduledTaskRegistrar.setScheduler(schedulerTheadPool());}/*** 线程池*
}
配置@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