预定任务不会打开我的罐子

时间:2017-06-20 08:55:30

标签: java windows cmd

我目前正在尝试创建一个计划任务,每分钟运行一次Jar文件。创建任务的命令行代码如下所示:

schtasks /Create /tn Testname /sc Minute /tr C:\Users\MyUser\Desktop\Program.jar

无论我等多久,都没有任何反应。计划任务GUI显示我的任务结果为(0x1)

如果我在CMD中运行C:\Users\MyUser\Desktop\Program.jar,一切正常

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我能够通过Java创建计划任务,我不知道这是否会在将来帮助某人,但万一我还是会发布我的代码:

private void createScheduledTask(String taskName) {
    List<String> commandList = new ArrayList<String>();
    commandList.add("schtasks.exe");
    commandList.add("/Create");
    commandList.add("/tn");
    commandList.add(taskName);
    commandList.add("/sc");
    commandList.add("Minute");
    commandList.add("/tr");
    commandList.add("java -jar C:\\Users\\MyUser\\Desktop\\Program.jar REPLACE_WITH_ARGUMENT");
    try {
        int returnValue = executeCMDStatement(commandList);
        if(returnValue == 0){
            //everything should have worked out
        } else {
            //there was an error 
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


public static int executeCMDStatement(List<String> commandList) throws InterruptedException, IOException {
    ProcessBuilder builder = new ProcessBuilder(commandList);
    Process process = builder.start();
    process.waitFor(3, TimeUnit.SECONDS);
    return process.exitValue();
}