springboot定时任务的快速应用

前言

定时任务在我们工作中应用非常广泛,在spring中定时任务实现可以用spring自己的 Scheduled 实现,也可以使用第三方框架 Quartz 来实现。 本文我们来看一下 Scheduled 的实现方式,通过简单的注解开启定时任务支持即可。

配置@EnableScheduling注解

  1. 我们新增一个定时的配置类,配置线程池,可选择配置拒绝策略。
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注解

  1. @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 ==============");
    }
}
  1. 同时也支持 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值