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秒执行一次");
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值