SpringBoot中使用Schedule

一、基本方法

有了SpringBoot貌似一切都变了非常简单,定时任务也不用整合quartz了,直接schedule就欧了。具体咋用?非常简单。

1、引入POM依赖

Spring的Schedule包含在spring-boot-starter模块中,无需引入其他依赖。

2、开启注解支持

在启动类增加注解:@EnableScheduling

3、轻松上手使用

A、Cron表达式

    // 当方法的执行时间超过任务调度频率时,调度器会在下个周期执行
    @Scheduled(cron = "0/10 * * * * *") 
    private void cronSchedule() {
		LOGGER.info("cronSchedule");
    }

B、固定间隔

    // 固定间隔,等上一次调度完成后,再开始计算间隔,再执行
    @Scheduled(fixedDelay = 5000) 
    public void fixedDelaySchedule() {
	    LOGGER.info("fixedDelaySchedule");
    }

C、固定频率

    // 固定频率,如果上次调度超过了频率时间,那么在其完成后,立刻执行
    @Scheduled(fixedRate = 3000) 
    public void fixedRateSchedule() {
    	LOGGER.info("fixedRateSchedule");
    }

二、注意要点

Spring的Schecule默认是单线程执行的,如果你定义了多个任务,那么他们将会被串行执行,会严重不满足你的预期。

所以为了解决该问题,需要自定义线程池,具体如下:

/**
 * 自定义线程池
 */
@Component
public class ScheduleConfig implements SchedulingConfigurer {

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		taskRegistrar.setScheduler(customScheduler());
	}

	@Bean(destroyMethod = "shutdown")
	public ExecutorService customScheduler() {
		return Executors.newScheduledThreadPool(20);
	}

}

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值