@Scheduled实现定时任务(实现多个定时任务并发执行)

@Scheduled实现定时任务

使用@Scheduled注解需要springboot启动类上添加注解@EnableScheduling
@SpringBootApplication
@MapperScan(basePackages = {"com.xxx.*.mapper"})
@EnableScheduling
public class PictureProcessingAdminApplication{
	public static void main(String[] args) {
		SpringApplication.run(PictureProcessingAdminApplication.class, args);
	}
}
同个任务的同步执行

同步执行:等待上一次定时任务结束后才开始cron表达式时间匹配

注意:同步任务所在类必须被spring扫描所管理才行,所以需要添加@Component注解。
很多人明明在方法在添加了@Scheduled注解,但是不生效都是这个原因,定时任务所在类没有被spring管理。

@Component
public class taskTest {

    @Scheduled(cron = "0 */1 * * * ?")
    public void task1(){
        try {
            System.out.println("任务1执行:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
            Thread.sleep(65000);
            System.out.println("任务1结束:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
同个任务的并发执行

相对同步执行来说,定时任务方法头部增加@Async即可实现并发执行,也就是严格按照cron表达式进行时间匹配执行,无需等待上一次任务执行结束。

@Component
public class taskTest {

    @Async
    @Scheduled(cron = "0 */1 * * * ?")
    public void task1(){
        try {
            System.out.println("任务1执行:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
            Thread.sleep(65000);
            System.out.println("任务1结束:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
多个任务的同步执行

任务使用@Scheduled
然后最重要的是,需要将springboot维护的ThreadPoolTaskScheduler定时任务线程池的长度设置为大于定时任务个数的值。然后ThreadPoolTaskScheduler默认长度为1。所以默认只有一个定时任务在跑。

源码如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

所以,需要将ThreadPoolTaskScheduler的长度修改即可,在项目启动时,设置长度,替换原本springboot管理的bean即可。

@Component
public class TaskSchedulerConfig {
 
	@Bean
	public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
		ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
		threadPoolTaskScheduler.setPoolSize(10);
		return threadPoolTaskScheduler;
	}
}
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值