springboot:定时任务本地测试正常,打包服务器上跑时运行两次,定时任务重复执行

首先需要排除的是war包下否存在多个启动类

我这边的项目引入了自己写的工具jar包,虽然项目代码下只有一个启动类,但是jar包由于为了方便测试未将jar包内启动类删去

本地测试时基本是指定启动类入口,所以不会启动两次,但是若将项目打成war包部署至服务器,则服务器扫描到两个启动类便会启动两次项目,所以定时任务也会重复执行

参考文档

https://blog.csdn.net/qq_35651901/article/details/80207742

https://blog.csdn.net/zga5312/article/details/103999022

若排除了war包中存在多个启动类的情况,可继续参考网上修改容器配置文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Java Spring Boot 中执行定时任务可以使用 Spring Framework 提供的 `@Scheduled` 注解来实现。以下是一些步骤: 1. 在你的 Spring Boot 应用程序中,创建一个带有 `@EnableScheduling` 注解的配置类。这个注解将启用 Spring 的定时任务功能。 ```java import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableScheduling public class AppConfig { } ``` 2. 创建一个带有定时任务方法的类,并使用 `@Scheduled` 注解来标记该方法。你可以设置定时任务执行间表达式,决定任务在什么执行。 ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyTask { @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨执行 public void executeTask() { // 执行定时任务的逻辑 } } ``` 在上面的例子中,定时任务 `executeTask` 方法使用了 `cron` 表达式来定义每天凌晨执行间表达式。 3. 确保你的定时任务类被正确扫描并注入到 Spring 容器中。你可以在应用程序的主类上添加 `@ComponentScan` 注解,以确保扫描到你的定时任务类。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = "com.example") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 在上面的例子中,`@ComponentScan` 注解将扫描 `com.example` 包及其子包中的组件。 现在,你的定时任务应该在指定的执行了。确保你的应用程序已经启动,并检查日志输出以确认定时任务执行情况。 这是一个简单的示例,你可以根据自己的需求调整定时任务执行间和逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值