执行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没有结束,后一个已经开始的情况 ,所以要考虑到同步的问题.