应用场景
在某个时间点重启项目
定时监控项目启动(可以用更好的方法)
解释
用法
可以写定时任务调用这个脚本
可以用系统界面调用这个脚本
参数
第一个参数是shell脚本的位置和名字,第二个是等这个脚本启动几分钟,第三个是否打印shell脚本的输出
主要代码
package com.boc.quartz.task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
@Component("scriptTask")
@Slf4j
public class ScriptTask {
/**
*
* @param shell_path shell脚本的位置和名字 当前路径下的脚本 './test.sh'
* @param wait_minutes 等几分钟
* @param printShellOut 是否打印脚本日志 N/Y
*/
public void callShell(String shell_path, Integer wait_minutes , String printShellOut) {
// 获取shell返回流
BufferedInputStream in = null;
// 字符流转换字节流
BufferedReader br = null;
if(printShellOut==null) printShellOut="N";
try{
//shell执行状态
// 定义传入shell脚本的参数,将参数放入字符串数组里
String cmds[] = new String[1];
cmds[0] = shell_path;
// 执行shell脚本
log.debug("Execute Shell : "+shell_path);
Process pcs = Runtime.getRuntime().exec(cmds);
try {
log.debug("Execute Shell ["+shell_path+"] wait "+wait_minutes+" MINUTES");
pcs.waitFor(wait_minutes, TimeUnit.MINUTES);
} catch (InterruptedException e) {
log.error("Execute Shell ["+shell_path+"] has Exception", e.getMessage());
}
log.debug("Execute ShellTask ["+shell_path+"] finished.");
if(printShellOut.toUpperCase().equals("Y")) {
log.debug("Execute ShellTask ["+shell_path+"] result print start.");
in = new BufferedInputStream(pcs.getInputStream());
// 字符流转换字节流
br = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = br.readLine()) != null) {
log.debug("ExecuteShellTask result:",line);
}
log.debug("Execute ShellTask ["+shell_path+"] result print end.");
}
}catch (Exception ex){
log.error("ShellTask Exception", ex.getMessage());
}finally {
// 关闭输入流
try {
if(printShellOut.toUpperCase().equals("Y")) {
br.close();
in.close();
}
}catch(Exception e) {
log.error("ShellTask Exception", e.getMessage());
}
}
}
}