Schedule or run a Windows task Tag(s): Environment


The easy way to deal with Windows task from Java is to use the utility schtasks.exe.

Complete documentation : http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/schtasks.mspx

This example create a task to execute a command file (test.cmd) at a given date, only once.

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TestWinScheduler {

public static void main(String args[]) throws IOException, InterruptedException {
  // schtasks /create /tn "HowToTask" /tr c:\temp\test.cmd /sc once /st 00:00:00 /sd 2022/01/01 /ru username /rp password

  List<String> commands = new ArrayList<String>();

  commands.add("schtasks.exe");
  commands.add("/CREATE");
  commands.add("/TN");
  commands.add("\"HowToTask\"");
  commands.add("/TR");
  commands.add("\"c:/temp/test.cmd\"");
  commands.add("/SC");
  commands.add("once");
  commands.add("/ST");
  commands.add("00:00:00");
  commands.add("/SD");
  commands.add("2022/10/10");
  commands.add("/RU");
  commands.add("username");
  commands.add("/RP");
  commands.add("password");

  ProcessBuilder builder = new ProcessBuilder(commands);
  Process p = builder.start();
  p.waitFor();
  System.out.println(p.exitValue()); // 0 : OK
                                     // 1 : Error
  }
}
If you have an error maybe it's because of an invalid parameter. Grab stdout and stderr to see the output. Add this code after the start() to debug the problem.
// stdout
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
  System.out.println(line);
}
//stderr
is = p.getErrorStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
  System.out.println(line);
}
To execute a task :
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TestWinScheduler {

public static void main(String args[]) throws IOException, InterruptedException {
  // schtasks /run /tn "HowToTask"

  List<String> commands = new ArrayList<String>();

  commands.add("schtasks.exe");
  commands.add("/RUN");
  commands.add("/TN");
  commands.add("\"HowtoTask\"");

  ProcessBuilder builder = new ProcessBuilder(commands);
  Process p = builder.start();
  p.waitFor();
  System.out.println(p.exitValue()); // 0 : OK
                                     // 1 : Error
  }
}

blog comments powered by Disqus