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 {
/*
* 定时任务 参数顺序: shell path wait时间(分钟) 是否打印shell输出(YN)
* */
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());
}
}
}
}
java 调用shh脚本 《可以用前端调用这个方法重启项目啥的》
于 2024-03-06 17:57:41 首次发布