今天的需求是这样,在项目里添加一个定时任务,要求没30秒查询一次后台服务是否在运行,如果没有运行则将服务拉起。
@Scheduled(cron = "0/30 * * * * ?")
public void servermmk() throws IOException, InterruptedException {
String line;
try
{
//查看服务是否正在运行
//shell脚本运行后循环判断有几条返回的数据 为3则程序未运行 为4则运行
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ps -ef|grep 服务名"});
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
int i=1;
while ((line = input.readLine()) != null) {
i++;
}
if(i==3){
//拉起服务
int j = Runtime.getRuntime().exec(new String[]{"bash","-c","拉起服务命令"}).waitFor();
}
}
至于为什么是3和4,因为运行项目之后,如果服务正在运行,则查出来有3条数据,i=1,i++;则为4;如果服务没有运行,则可以查出来两条数据,则i=3.