【问题标题】:Spring scheduling for multiple different times多个不同时间的春季调度
【发布时间】:2021-08-28 21:21:12
【问题描述】:

我目前正在做一个项目,以在用户点击时自动抓取网页内容,但我遇到的问题是我需要在不同的时间和不同的秒数内运行这些方法。我参考了@Schedule 和 TimerTask,但它们只能在固定时间工作。我的情况有什么解决办法吗?

代码示例:

public void run(String selectedWeb) {
   if(selectedWeb.equals("First Web")) {
      scrapeFirstWeb(); //Need this method auto execute on 8, 30, 42 seconds every minute
   }else if(selectedWeb.equals("Second Web")) {
      scrapeSecondWeb(); //Need this method auto execute on 10am, 1pm, 11pm every day
   }    
}

PS:我之前在 cron 中使用过 @Scheduled 注解,但是有一个问题是这个注解会自动运行所有的方法,包括那些我没有选择运行的方法。因为我可能只刮第一网或第二网而不是两者,但是注释将忽略您选择的网,时间到了它也会执行。所以这是我的问题。

如果有人知道有什么方法可以让@Schedule 注释运行我选择的方法只能做评论让我知道,提前谢谢!

【问题讨论】:

  • 在设置了 Cron 值的两种不同方法上使用 @Schedule 注释有什么挑战吗?
  • @MishraJi 我也尝试过使用带有 cron 的 Schedule,但是有一个问题是这个注释会自动运行我没有选择运行的方法 include。因为我可能有只废弃第一个 Web 或第二个 Web 的情况,但是注释会忽略您选择的 Web,它何时会按时运行......或者有什么方法可以让 Schedule annotation 仅针对所选方法运行?
  • 您可以在多个方法上使用类似 cron 的时间规范运行,每个方法都做自己的事情。

标签: java spring-boot scheduled-tasks


【解决方案1】:

我建议使用可以随时停止的调度执行器:

 ScheduledExecutorService executorService = Executors
                .newSingleThreadScheduledExecutor();
        ScheduledFuture<?> in_method1 = executorService.scheduleAtFixedRate(() -> System.out.println("In method1"), 5, 3, TimeUnit.SECONDS);

        Thread.sleep(10000);
        in_method1.cancel(false);

【讨论】:

  • 我不需要停止它,但需要它像我上面的示例代码一样在几个不同的时间自动运行
  • 因此您应该捕获一个调度程序应该何时启动(然后执行 scheduleAtFixedRate 或类似操作)以及另一个调度程序应该何时停止(然后执行取消)
  • 例如:if(selectedWeb.equals("First Web")) { executer1.schedulerFixedRate();执行2.cancel() }
【解决方案2】:

我终于找到了解决这个问题的方法,它也可以使用后面的@Schedule注解。

//Set @Scheduled annotation to false to avoid it auto execute when compile
@Value("${jobs.enabled:false}")
private boolean isEnabled;

public void run(String selectedWeb) {
   if(selectedWeb.equals("First Web")) {
      //Set it back to true when it has been selected
      isEnabled = true
      scrapeFirstWeb();
   }else if(selectedWeb.equals("Second Web")) {
      isEnabled = true
      scrapeSecondWeb();
   }    
}

@Scheduled(cron = "8,30,42 * * * * *")
    public void scrapeFirstWeb(){
    //So when isEnabled is false, it will not doing anything until it is true
    if(isEnabled){
       //Do something
    }
}

详细解释可以参考这里https://www.baeldung.com/spring-scheduled-enabled-conditionally

【讨论】:

    猜你喜欢
    • 2015-08-31
    • 2020-07-11
    • 2020-01-21
    • 2018-09-19
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多