繁体   English   中英

如何使用Spring Boot批处理过程运行.bat文件

[英]How to run .bat file using spring boot batch process

我有一个批处理文件,该文件正在Windows任务计划程序中运行,它将每隔10小时重复执行一次jar文件。

现在,我尝试使用Spring Boot批处理过程作为任务调度程序来运行相同的批处理文件。 但是我没有得到解决方案。

我该如何解决这个问题?

在您的计划方法中,尝试这样:

Runtime.getRuntime().exec("file.bat");

您是否尝试过这个https://spring.io/guides/gs/scheduling-tasks/

Spring Boot调度程序可以调度您的任务,并接受类似CRON的表达式来调度重复任务。

您可以使用Java ProcessBuilder API触发批处理(.bat)文件

您可以执行以下简单的Spring调度任务

@Component
public class RunCommandScheduledTask {

    private final ProcessBuilder builder;
    private final Logger logger; //  Slf4j in this example
    // inject location/path of the bat file 
    @Inject
    public RunCommandScheduledTask(@Value("${bat.file.path.property}") String pathToBatFile) {
        this.builder = new ProcessBuilder(pathToBatFile);
        this.logger = LoggerFactory.getLogger("RunCommandScheduledTask");
    }
    // cron to execute each 10h 
    @Scheduled(cron = "0 */10 * * *")
    public void runExternalCommand() {
        try {
            final Process process = builder.start();
            if (logger.isDebugEnabled()) {
                // pipe command output and proxy it into log
                try (BufferedReader out = new BufferedReader(
                        new InputStreamReader(process.getInputStream(), StandardCharsets.ISO_8859_1))) {
                    String str = null;
                    for (;;) {
                        str = out.readLine();
                        if (null == str)
                            break;
                        logger.debug(str);
                    }
                }
            }
            process.waitFor();
        } catch (IOException exc) {
            logger.error("Can not execute external command", exc);
        } catch (InterruptedException exc) {
            Thread.currentThread().interrupt();
        }
    }

}

.....
@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }
}

暂无
暂无

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

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