SpringBoot如何整合定时任务调度

2025-11-09 14:08:49

1、所有的系统开发里面定时调度绝对是一个核心的话题,对于定时调用的实现在实际开发之中可以使用:TimerTask,Quartz,SpringTask配置,实际上这里面最简单的配置就是Spring自己所提供的Task处理。

如果要想实现定时调度,只需要配置一个定时调度的组件类即可:

package com.gwolf.task;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

import java.time.Instant;

@Component

public class MyScheduler {

    @Scheduled(fixedRate = 2000) //采用间隔调用

    public void runJobA() {

        System.out.println("[MyTaskA-间隔调度***" + Instant.now());

    }

    

    @Scheduled(cron = "* * * * * ?")

    public void runJobB() {

        System.err.println("[MyTaskB-定时调度调度***" + Instant.now());

    }

}

SpringBoot如何整合定时任务调度

2、如果现在要想执行此任务,那么还需要有一个基本的前提:你的程序启动类上一定要启用调度处理。

package com.gwolf;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.context.embedded.EmbeddedServletContainer;

import org.springframework.scheduling.annotation.EnableScheduling;

import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication  //启动SpringBoot程序,而后自带子包扫描。

@EnableTransactionManagement

@EnableScheduling

public class StartSpringBootMain {

    public static void main(String[] args) {

        SpringApplication.run(StartSpringBootMain.class, args);

    }

}

SpringBoot如何整合定时任务调度

3、启动程序运行主类,查看程序的执行结果:

SpringBoot如何整合定时任务调度

4、这个时候所实现的任务调用只是串行任务调度,也就是说所有的任务时候一个一个的执行的处理方式,那么如果现在有一个任务所花费的时间特别的畅,则其他的任务都会挤压,实际开发之中很明显这种处理是不可能存在。

SpringBoot如何整合定时任务调度

5、如果要想启动并行的调度处理,则一定要准备出一个线程调度池,进行一个线程调度的配置类:

package com.gwolf.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.annotation.SchedulingConfigurer;

import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;

@Configuration

public class SchedulerConfig implements SchedulingConfigurer{

    //开启一个线程调度池

    @Override

    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(100));

    }

}

SpringBoot如何整合定时任务调度

6、在以后所编写的定时任务调用的时候一定要准备好一个线程池,这样才可以让多个任务并行执行。

SpringBoot如何整合定时任务调度

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢