如何在springboot应用程序中动态打开/关闭调度方法

时间:2017-06-09 18:32:36

标签: java spring-boot spring-scheduled

我正在构建一个Springboot应用程序,我想从前端打开一个预定的方法。 (因为我希望调度程序只在从前端调用方法后运行)

此计划方法将使用给定参数调用Web服务并继续运行,直到收到特定响应("成功")。

一旦收到特定的响应,我希望预定的方法停止运行,直到从前端再次调用它。

我不知道如何启动和停止执行预定方法。

我目前有这个:

@Component
public class ScheduledTasks {

    private static final Logger LOG = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void waitForSuccess(String componentName) {
        LOG.info("Running at: " + dateFormat.format(new Date()));
        String response = MyWebService.checkStatus(componentName);
        if ("success".equalsIgnoreCase(response)) {
            LOG.info("success");
            //Stop scheduling this method
        } else {
            LOG.info("keep waiting");
        }
    }
}

这是我的控制器,通过它来打开预定的方法:

@Controller
public class MainController {

    @GetMapping(/start/{componentName})
    public @ResponseBody String startExecution(@PathVariable String componentName) {
        //do some other stuff
        //start scheduling the scheduled method with the parameter 'componentName'
        System.out.println("Waiting for response");
    }

}

我的方法是否正确?如何使用springboot和schedulers实现此功能?

2 个答案:

答案 0 :(得分:3)

以下是Spring Boot中计划方法的启动/停止API的完整示例。您可以使用此类API:
http:localhost:8080 / start - 用于启动固定费率为5000毫秒的预定方法 http:localhost:8080 / stop - 用于停止预定的方法

[2017-09-27 09:54:26] request.INFO: Matched route "newsfeedMessage". {"route":"newsfeedMessage","route_parameters":{"_controller":"CP\\FeedBundle\\Controller\\FeedController::newsfeedMessageAction","_route":"newsfeedMessage"},"request_uri":"https://www.website.local:8443/newsfeedMessage","method":"GET"} []
[2017-09-27 09:54:26] request.INFO: Matched route "blog_feed_item". {"route":"blog_feed_item","route_parameters":{"_controller":"CP\\FeedBundle\\Controller\\FeedController::blogFeedItemAction","_route":"blog_feed_item"},"request_uri":"https://www.website.local:8443/blog-feed-item","method":"GET"} []
...
and so on ...
...

答案 1 :(得分:0)

Use Tomcat installation (takes control of Tomcat installation)