1. 程式人生 > >使用Java定時執行shell指令碼

使用Java定時執行shell指令碼

執行shell指令碼

  • Runtime.getRuntime().exec() 可以直接執行部分命令,不過執行一個shell指令碼的話更方便修改
    public static void  runshell(String path){
        try {
            String getX="chmod a+x "+path;
            // 給予執行許可權
            Process process =Runtime.getRuntime().exec(getX);
            process.waitFor();
            //執行指令碼
process=Runtime.getRuntime().exec("bash "+path); process.waitFor(); //獲取執行結果 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder stringBuilder= new StringBuilder(); String line; while
(( line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append("\n"); } //輸出執行結果 System.out.println(stringBuilder.toString()); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }

Java中的定時任務

  • TimerTask是一個定時任務類, 需要重寫 run()方法,其中為將要定時執行的操作,在這裡是列印當前時間,執行 runshell() 方法

  • TImer是一個定時器類,scheduleAtFixedRate()方法根據傳入的引數定時執行timertask , 三個引數分別為

    • TimerTask task : 要執行的任務
    • long delay || Date firstTime : 等待delay 毫秒執行第一次 || 在firstTime時執行第一次
    • long period: 每次執行的時間間隔
    public static void main(String[] paths) {
        String path;
        //有引數
        if (paths.length>0){
            path=paths[0];
        }
        else {
            path="do.sh";
        }

        TimerTask task=new TimerTask() {
            @Override
            public void run() {
                System.out.println("now : "+ LocalDateTime.now());
                runshell(path);
            }
        };
        Timer timer=new Timer();
        long delay=0;
        long period=1000*2;
        timer.scheduleAtFixedRate(task,delay,period);
    }
  • 使用 scheduleAtFixedRate() 時,可能出現前一個task沒有結束,後一個已經開始的情況 ,所以要考慮到同步的問題.