springmvc和springboot定时任务@Scheduled配置多线程

  1. spring的@Scheduled定时任务默认是单线程,多个任务执行起来时间会有问题:B任务会因为A任务执行起来需要20S而被延后20S执行。
  2. springmvc配置定时任务为多线程只需要两步,配置文件修改如下配置:

<!-- 配置执行器 -->

task:executor/@pool-size:可以指定执行线程池的初始大小、最大大小 .
           task:executor/@queue-capacity:等待执行的任务队列的容量 
           task:executor/@rejection-policy:当等待队列爆了时的策略,分为丢弃、由任务执行器直接运行等方式

<task:executor id="executor" keep-alive="3600" pool-size="100-200" queue-capacity="500" rejection-                       policy="CALLER_RUNS" />

<!-- 配置任务线程池 -->

<task:scheduler id="schedulerTest" pool-size="10" />

<!-- 启用annotation方式 -->

<task:annotation-driven scheduler="schedulerTest" executor="executor"/>

  1. springboot配置定时任务为多线程如下:
  • 开启缓存注解

 

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

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

 

  • 配置多线程

 

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
    }
}

 

  • 编写定时任务
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class CustomerLevelTest {
    @Scheduled(cron="0/5 * * * * ? ")   //每5秒执行一次 
    public void testCron() {
       DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        System.err.println (Thread.currentThread ().getName ()+"="+sdf.format(new Date())+"*********每5秒执行一次");
    }
    @Scheduled(cron="0/4 * * * * ? ")   //每5秒执行一次 
    public void testCron4() {
       DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        System.err.println (Thread.currentThread ().getName ()+"="+sdf.format(new Date())+"*********每4秒执行一次");
    }
}
SpringMVCSpringBoot是两个在Java开发中常用的框架,它们有以下不同之处: 1. 定位和设计目标: - SpringMVC是基于Spring框架的MVC(Model-View-Controller)模式的Web框架,用于构建传统的Java Web应用程序。 - SpringBoot是一个用于简化Spring应用程序开发的框架,旨在提供快速、方便的配置和部署。 2. 配置方式: - SpringMVC需要手动配置各种组件,如DispatcherServlet、HandlerMapping、ViewResolver等,需要编写大量的XML或Java配置。 - SpringBoot采用约定优于配置的原则,通过自动配置和默认值,减少了开发者的配置工作量。只需添加一些必要的依赖和少量的配置,即可快速搭建一个可运行的应用。 3. 依赖管理: - SpringMVC需要手动管理各种依赖,需要引入大量的jar包,并手动解决版本冲突等问题。 - SpringBoot通过提供一组预定义的starter依赖,简化了依赖管理。只需引入相关starter依赖,SpringBoot会自动解决依赖关系和版本冲突。 4. 内嵌服务器: - SpringMVC需要手动配置和部署外部的Web服务器,如Tomcat、Jetty等。 - SpringBoot内置了常用的Web服务器,如Tomcat、Jetty等,可以直接以独立应用的形式运行,无需额外配置和部署。 5. 开发体验: - SpringMVC需要开发者手动编写大量的配置和代码,相对繁琐。 - SpringBoot通过自动配置和约定优于配置的原则,简化了开发过程,提供了更好的开发体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值