Spring Batch 中XML调用CMD的方法

在SpringBatch中调用cmd,有以下两种常用方法

  1. 新定义一个Tasklet类,在里面用调用cmd。[1]
demoTasklet.java

Runtime rt = Runtime.getRuntime();
Process p = rt.exec("cmd.exe /c start demo.bat");
System.out.println(p.toString());
  1. 通过SpringBatch所提供的自带的Tasklet来调用cmd。
demoJob.xml


<!-- ===================================== -->
<!-- ========        JOB          ======== -->
<!-- ===================================== -->
<batch:job id="jobStartCmd">
    <batch:step id="jobStartCmdStep">
        <batch:tasklet ref="jobStartCmdTasklet"/>
    </batch:step>
</batch:job>

<bean id="jobStartCmdTasklet" class="org.springframework.batch.core.step.tasklet.SystemCommandTasklet" scope="step">
    <property name="command" value="cmd.exe /c start demo.bat"/>
    <property name="environmentParams" value="001"/>
    <property name="workingDirectory" value="D:\demo"/>
    <property name="timeout" value="1000"/>
</bean>

通过调用SpringBatch框架封装好的==SystemCommandTasklet==类来调用cmd,上面四个参数中,"command","workingDirectory","timeout"为必填参数。

下面附上SystemCommandTasklet的源代码,可以看出,通过该方法来执行cmd,实际上也是应用

Runtime.getRuntime().exec(command, environmentParams, workingDirectory);

来进行实现的。所以,具体用哪种方法去调用cmd比较方便,就是仁者见仁智者见智了。

/*
 * Copyright 2006-2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.batch.core.step.tasklet;

import java.io.File;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobInterruptedException;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.listener.StepExecutionListenerSupport;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.util.Assert;

/**
 * {@link Tasklet} that executes a system command.
 * 
 * The system command is executed asynchronously using injected
 * {@link #setTaskExecutor(TaskExecutor)} - timeout value is required to be set,
 * so that the batch job does not hang forever if the external process hangs.
 * 
 * Tasklet periodically checks for termination status (i.e.
 * {@link #setCommand(String)} finished its execution or
 * {@link #setTimeout(long)} expired or job was interrupted). The check interval
 * is given by {@link #setTerminationCheckInterval(long)}.
 * 
 * When job interrupt is detected tasklet's execution is terminated immediately
 * by throwing {@link JobInterruptedException}.
 * 
 * {@link #setInterruptOnCancel(boolean)} specifies whether the tasklet should
 * attempt to interrupt the thread that executes the system command if it is
 * still running when tasklet exits (abnormally).
 * 
 * @author Robert Kasanicky
 */
public class SystemCommandTasklet extends StepExecutionListenerSupport implements Tasklet, InitializingBean {

    protected static final Log logger = LogFactory.getLog(SystemCommandTasklet.class);

    private String command;

    private String[] environmentParams = null;

    private File workingDirectory = null;

    private SystemProcessExitCodeMapper systemProcessExitCodeMapper = new SimpleSystemProcessExitCodeMapper();

    private long timeout = 0;

    private long checkInterval = 1000;

    private StepExecution execution = null;

    private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();

    private boolean interruptOnCancel = false;

    /**
     * Execute system command and map its exit code to {@link ExitStatus} using
     * {@link SystemProcessExitCodeMapper}.
     */
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

        FutureTask<Integer> systemCommandTask = new FutureTask<Integer>(new Callable<Integer>() {

            public Integer call() throws Exception {
                Process process = Runtime.getRuntime().exec(command, environmentParams, workingDirectory);
                return process.waitFor();
            }

        });

        long t0 = System.currentTimeMillis();

        taskExecutor.execute(systemCommandTask);

        while (true) {
            Thread.sleep(checkInterval);
            if (systemCommandTask.isDone()) {
                contribution.setExitStatus(systemProcessExitCodeMapper.getExitStatus(systemCommandTask.get()));
                return RepeatStatus.FINISHED;
            }
            else if (System.currentTimeMillis() - t0 > timeout) {
                systemCommandTask.cancel(interruptOnCancel);
                throw new SystemCommandException("Execution of system command did not finish within the timeout");
            }
            else if (execution.isTerminateOnly()) {
                systemCommandTask.cancel(interruptOnCancel);
                throw new JobInterruptedException("Job interrupted while executing system command '" + command + "'");
            }
        }

    }

    /**
     * @param command command to be executed in a separate system process
     */
    public void setCommand(String command) {
        this.command = command;
    }

    /**
     * @param envp environment parameter values, inherited from parent process
     * when not set (or set to null).
     */
    public void setEnvironmentParams(String[] envp) {
        this.environmentParams = envp;
    }

    /**
     * @param dir working directory of the spawned process, inherited from
     * parent process when not set (or set to null).
     */
    public void setWorkingDirectory(String dir) {
        if (dir == null) {
            this.workingDirectory = null;
            return;
        }
        this.workingDirectory = new File(dir);
        Assert.isTrue(workingDirectory.exists(), "working directory must exist");
        Assert.isTrue(workingDirectory.isDirectory(), "working directory value must be a directory");

    }

    public void afterPropertiesSet() throws Exception {
        Assert.hasLength(command, "'command' property value is required");
        Assert.notNull(systemProcessExitCodeMapper, "SystemProcessExitCodeMapper must be set");
        Assert.isTrue(timeout > 0, "timeout value must be greater than zero");
        Assert.notNull(taskExecutor, "taskExecutor is required");
    }

    /**
     * @param systemProcessExitCodeMapper maps system process return value to
     * <code>ExitStatus</code> returned by Tasklet.
     * {@link SimpleSystemProcessExitCodeMapper} is used by default.
     */
    public void setSystemProcessExitCodeMapper(SystemProcessExitCodeMapper systemProcessExitCodeMapper) {
        this.systemProcessExitCodeMapper = systemProcessExitCodeMapper;
    }

    /**
     * Timeout in milliseconds.
     * @param timeout upper limit for how long the execution of the external
     * program is allowed to last.
     */
    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }

    /**
     * The time interval how often the tasklet will check for termination
     * status.
     * 
     * @param checkInterval time interval in milliseconds (1 second by default).
     */
    public void setTerminationCheckInterval(long checkInterval) {
        this.checkInterval = checkInterval;
    }

    /**
     * Get a reference to {@link StepExecution} for interrupt checks during
     * system command execution.
     */
    @Override
    public void beforeStep(StepExecution stepExecution) {
        this.execution = stepExecution;
    }

    /**
     * Sets the task executor that will be used to execute the system command
     * NB! Avoid using a synchronous task executor
     */
    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    /**
     * If <code>true</code> tasklet will attempt to interrupt the thread
     * executing the system command if {@link #setTimeout(long)} has been
     * exceeded or user interrupts the job. <code>false</code> by default
     */
    public void setInterruptOnCancel(boolean interruptOnCancel) {
        this.interruptOnCancel = interruptOnCancel;
    }

}


  1. cmd /c dir 是执行完dir命令后关闭命令窗口。
    cmd /k dir 是执行完dir命令后不关闭命令窗口。
    cmd /c start dir 会打开一个新窗口后执行dir指令,原窗口会关闭。
    cmd /k start dir 会打开一个新窗口后执行dir指令,原窗口不会关闭。
    可以用cmd /?查看帮助信息。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,651评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,468评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,931评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,218评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,234评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,198评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,084评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,926评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,341评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,563评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,731评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,430评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,036评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,676评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,829评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,743评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,629评论 2 354

推荐阅读更多精彩内容

  • .bat脚本基本命令语法 目录 批处理的常见命令(未列举的命令还比较多,请查阅帮助信息) 1、REM 和 :: 2...
    庆庆庆庆庆阅读 8,094评论 1 19
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,380评论 0 5
  • 运行操作 CMD命令:开始->运行->键入cmd或command(在命令行里可以看到系统版本、文件系统版本) CM...
    小明yz阅读 2,760评论 0 8
  • 个人学习批处理的初衷来源于实际工作;在某个迭代版本有个BS(安卓手游模拟器)大需求,从而在测试过程中就重复涉及到...
    Luckykailiu阅读 4,717评论 0 11
  • “ 每逢过节胖三斤 ”这句口头禅一直萦绕耳边。别说过节,就是平常都会因为吃个夜宵而长胖,于是,减肥食谱加运动...
    faye26阅读 414评论 0 1