How to create a scheduler task in Window Task Scheduler using Java?

后端 未结 3 1336
春和景丽
春和景丽 2021-01-19 06:09

I want to create a task under Window Task Scheduler using my java code. OS I am using is win7 64bit. After creating the task I have to edit the scheduled time weekly or biwe

3条回答
  •  梦谈多话
    2021-01-19 06:51

    Launch the command line utility schtasks.

    To create the 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 /create /tn "HowToTask" /tr c:\temp\test.cmd /sc once /st 00:00:00 /sd 2022/01/01 /ru username /rp password
    
      List commands = new ArrayList();
    
      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
      }
    }
    

    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 commands = new ArrayList();
    
      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
      }
    }
    

    Ref

提交回复
热议问题