springboot使用Scheduled定时任务

一、单线程使用Scheduled

  1. 在启动类Application上加@EnableSchedulin注解,开启spring定时任务
  2. 创建任务类,加@Component注解
  3. 在方法上加@Scheduled()注解,有以下三种方式
	// corn模式
 	@Scheduled(cron = "0 0 0 0/1 * ?")
 	// fixedDelay:在上一次任务执行完成后几豪秒再执行,
 	// initialDelay:应用启动后延迟几豪秒执行该任务
	@Scheduled(initialDelay =2000,fixedDelay = 2000)
	// fixedRate 在上一次任务执行开始后几豪秒执行,
	@Scheduled(initialDelay =2000,fixedRate = 5000)

***注意:***这里的所有任务都是用一个线程执行,因为spring的Scheduled默认线程数目=1,所有这里不支持多线程

二、多线程使用Scheduled

  1. 修改spirng原生的Scheduled的线程池配置,使其满足需要的多线程以及其他功能

    1. 使用配置文件修改配置

      spring:
        http:
          task:
            scheduling:
              pool:
                # 线程数目
                size: 3
                # 任务名称
              thread-name-prefix: 定时任务
              # 应用关闭时,是否等待定时任务执行完成。默认为 false ,建议设置为 true
              shutdown:
                await-termination: true
                # 等待任务完成的最大时长,单位为秒。默认为 0 ,根据自己应用来设置
                await-termination-period: 60
      
    2. 使用配置类

      @Slf4j
      @Configuration
      public class ScheduledConfig {
      
      	// 配置定时任务线程池
      	@Bean
      	public ThreadPoolTaskScheduler taskScheduler() {
      		ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
      		executor.setPoolSize(5);
      		executor.setThreadNamePrefix("定时任务-");
      		// executor.setth
      		// 应用关闭时,是否等待定时任务执行完成。默认为 false ,建议设置为 true
      		executor.setWaitForTasksToCompleteOnShutdown(true);
      		// 等待任务完成的最大时长,单位为秒。默认为 0 ,根据自己应用来设置
      		executor.setAwaitTerminationSeconds(120);
      		return executor;
      	}
      }
      
  2. 使用异步线程池

    创建线程池,并在@Scheduled()@Async注解,

    注意:使用了异步后,fixedDelay模式无法生效,所以如果有这个模式,不能加@Async

    	@Async
    	@Scheduled(cron = "0 0 0 0/1 * ?")
    	public void excute() {
    		//dosomething
    	}
    
    @Slf4j
    @Configuration
    @EnableAsync
    public class AsyncConfig { //implements AsyncConfigurer
    
        @Value(value = "${async.corePoolSize}")
        private int corePoolSize;
    
        @Value(value = "${async.maxPoolSize}")
        private int maxPoolSize;
    
        @Value(value = "${async.queueCapacity}")
        private int queueCapacity;
        //
        //@Autowired
        //private HttpTaskRejectHandler httpTaskRejectHandler;
    
        //如果Bean名字不是taskExecutor,就用在@Async("httpTaskExecutor")这里加上名字。
        @Bean
        public ThreadPoolTaskExecutor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(corePoolSize);
            executor.setMaxPoolSize(maxPoolSize);
            executor.setQueueCapacity(queueCapacity);
            executor.setThreadNamePrefix("异步任务——");
            //队列满,线程被拒绝执行策略,打印
            // executor.setRejectedExecutionHandler(httpTaskRejectHandler);
            //队列满,丢弃最老的任务
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
            executor.initialize();
            return executor;
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值