springboot的定时任务的方法周期比方法的运行时间长

简介: springboot的定时任务的方法周期比方法的运行时间长

文章提出


在写一个从接口中读取实时数据然后存到自己数据库的小demo时候,发现数据从某一天到现在的都停止了。


先说一下上面读数据存数据的简单逻辑:定时任务从redis中读取上次读取到的时间点timeA,然后从timeA每次加1小时访问接口读取这一小段的代码,然后发现某一小时timeB没数据,把这个时间timeB存到redis中,到下次定时任务的时候在调用。


我的操作就是找到最早没有读到的时间点,然后修改redis中的时间点,启动定时任务就好了。


but   因为间隔的时间比较长,所以任务方法执行的时间超过了定时任务的周期,那么问题来了???


比如我定时任务是每一小时执行一次,我方法执行了1.5个小时。项目从1点启动,1点开始执行定时任务,那么2点的时候任务还没有执行完毕,那么任务是否又开启一个???


代码实操


测试代码1


@Component
public class TaskComponent {
    /**
     * 任务周期是2秒
     * 任务执行时间是3秒
     */
    @Scheduled(cron = "0/2 * * * * ?  ")//每2秒执行一次
    public void sendMessage() {
        System.out.println("定时任务开始执行: " + LocalDateTime.now());
        try {
            TimeUnit.SECONDS.sleep(3);
            System.out.println("(业务逻辑)发送消息: " + LocalDateTime.now());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


@SpringBootApplication
@EnableScheduling
public class ScheduleDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleDemoApplication.class, args);
    }
}


1.png


测试代码2


@Component
public class TaskComponent {
    /**
     * 任务周期是2秒
     * 任务执行时间是3秒
     */
    @Scheduled(cron = "0/2 * * * * ?  ")//每2秒执行一次
    @Async
    public void sendMessage() {
        System.out.println("定时任务开始执行: " + LocalDateTime.now());
        try {
            TimeUnit.SECONDS.sleep(3);
            System.out.println("(业务逻辑)发送消息: " + LocalDateTime.now());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


@SpringBootApplication
@EnableScheduling
@EnableAsync
public class ScheduleDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleDemoApplication.class, args);
    }
}


2.png


结论


1)如测试代码1,默认情况下,当定时任务的周期小于方法的执行时间时,定时任务会跳过方法还没有执行完毕的那次(比如我规定1小时执行一次,但是任务的执行时间是1.5小时。当前时间为0点,开始执行定时任务,但是当到1点时候又该执行定时任务了,但是该定时任务还没有执行完,所以跳过。下次执行就是2点的时候了)


2)如测试代码2,如果要实现无论任务是否执行完,都开启新任务的需求,@EnableAsync  @Async


目录
相关文章
|
2月前
|
人工智能 JSON 前端开发
Spring Boot解决跨域问题方法汇总
Spring Boot解决跨域问题方法汇总
|
2月前
|
存储 NoSQL Java
Spring Boot统计一个Bean中方法的调用次数
Spring Boot统计一个Bean中方法的调用次数
60 1
|
2月前
|
SQL 监控 druid
p6spy【SpringBoot集成】使用p6spy-spring-boot-starter集成p6spy监控数据库(配置方法举例)
p6spy【SpringBoot集成】使用p6spy-spring-boot-starter集成p6spy监控数据库(配置方法举例)
431 0
|
3天前
|
存储 NoSQL Java
教程:Spring Boot与RocksDB本地存储的整合方法
教程:Spring Boot与RocksDB本地存储的整合方法
|
7天前
|
缓存 监控 NoSQL
SpringBoot配置第三方专业缓存技术jetcache方法缓存方案
SpringBoot配置第三方专业缓存技术jetcache方法缓存方案
22 1
|
11天前
|
Java Spring
在Spring Boot中,可以通过控制`@PostConstruct`注解方法的执行顺序来实现初始化时的顺序控制
在Spring Boot中,可以通过控制`@PostConstruct`注解方法的执行顺序来实现初始化时的顺序控制
29 1
|
22天前
|
Java 调度 Spring
SpringBoot多个@Scheduled注解的方法,会阻塞吗
【6月更文挑战第9天】SpringBoot多个@Scheduled注解的方法,会阻塞吗
22 5
|
3天前
|
消息中间件 Java 机器人
Spring Boot与NATS消息系统的集成方法
Spring Boot与NATS消息系统的集成方法
|
2月前
|
Java 微服务 Spring
Spring Boot中获取配置参数的几种方法
Spring Boot中获取配置参数的几种方法
33 2
|
2月前
|
Java 应用服务中间件
SpringBoot 项目war包部署 配置外置tomcat方法
SpringBoot 项目war包部署 配置外置tomcat方法
90 0