简体   繁体   English

某些方法完成后如何启动/停止@Scheduled 任务

[英]How to start/stop @Scheduled task after certain method finishes

I have a scheduled task that start working when application context loads and runs forever until program ends.我有一个计划任务,它在应用程序上下文加载并永远运行直到程序结束时开始工作。

I'd like to save some resources and run scheduled task only when it's needed.我想节省一些资源并仅在需要时运行计划任务。

Here is abstract code I imagine how it should work like.这是我想象它应该如何工作的抽象代码。

@EnableScheduling    
public class Scheduling {
    
        @Scheduled(fixedRate = 1000)
        public void scheduledTask() {
           log.info("scheduled task has been started");
        }
    
        public void triggerStart() {
           log.info("after this @Scheduled task will start working");
        }
    
        public void triggerFinish() {
           log.info("after this @Scheduled task will stop working");
        }
}

I'm curious is it possible to achieve such result?我很好奇是否有可能达到这样的结果?

A very simple way is to add a boolean switch:一个非常简单的方法是添加一个 boolean 开关:

@Scheduled(fixedRate = 1000)
public void scheduledTask() {
   if (enabled) {
       log.info("scheduled task has been started");
   }
}

public void triggerStart() {
   enabled = true;
   log.info("after this @Scheduled task will start working");
}

public void triggerFinish() {
   enabled = false;
   log.info("after this @Scheduled task will stop working");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM