• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

springboot最实现多线程定时任务

武飞扬头像
好怪~
帮助3

一、为什么会有多线程定时任务

       默认情况下,Spring Boot定时任务是按单线程方式执行的,也就是说,如果同一时刻有两个定时任务需要执行,那么只能在一个定时任务完成之后再执行下一个。如果只有一个定时任务,这样做肯定没问题;当定时任务增多时,如果一个任务被阻塞,则会导致其他任务无法正常执行。要解决这个问题,需要配置任务调度线程池。

二、如何编写多线程定时任务

1、开启定时任务:首先在主启动类上加注解

@EnableScheduling

学新通
2、通过ScheduleConfig配置文件实现SchedulingConfigurer接口,并重写setSchedulerfang方法。

package com.zkyq.obd.config.handler;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;

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

3、编写多个定时任务

    @Scheduled(cron="0/1 * * * * ? ")  //每1秒执行一次
    public void testCron2() {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info (sdf.format(new Date()) "*********每1秒执行一次");
    }
    @Scheduled(cron="0/1 * * * * ? ")  //每1秒执行一次
    public void testCron3() {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info(sdf.format(new Date()) "*********第2秒执行一次");
    }
    @Scheduled(cron="0/1 * * * * ? ")  //每1秒执行一次
    public void testCron1() {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       log.info (sdf.format(new Date()) "*********第3秒执行一次");
    }

4、执行结果
学新通
关于多线程定时任务的使用就这些了,希望对大家有帮助。关注我,只分享干活教程!

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfhfaef
系列文章
更多 icon
同类精品
更多 icon
继续加载