通过springboot写的一个任务调度,执行linux的shell脚本。
1.application.properties
#日志的路径(自行定义)
logging.path=/app/storm/bin/start_logs
# 指定文件中日志输出的格式
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} ==== %msg%n
package com.renwu.demo.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Date;
@Component
public class MyTask3 {
//日志
Logger logger = LoggerFactory.getLogger(getClass());
/**
* 关闭
*/
@Scheduled(cron = "0 0 0/3 * * ?") //每隔三个小时执行一次函数
@Order(1) //组件的加载顺序
public void execute(){
try {
String shpath="/app/storm/bin/storm_stop.sh"; //shell路径
Process process =null;
String command1 = "chmod 777 " + shpath; //权限
process = Runtime.getRuntime().exec(shpath);
process.waitFor();
} catch (IOException e) {
logger.error("停止时间错误"+new Date()+":"+e.getMessage());
} catch (InterruptedException e) {
logger.error("停止时间错误"+new Date()+":"+e.getMessage());
}
logger.info("停止时间:"+new Date());
System.out.println("停止时间:"+new Date());
}
/**
* 开启
*/
@Scheduled(cron = "50 0 0/3 * * ?") //每隔3小时50秒执行一次函数
@Order(2)
public void execute1(){
try {
String shpath="/app/storm/bin/storm_start.sh"; //程序路径
Process process =null;
//String command1 = "chmod 777 " + shpath;
process = Runtime.getRuntime().exec(shpath);
process.waitFor();
} catch (IOException e) {
logger.error("开启时间错误"+new Date()+":"+e.getMessage());
} catch (InterruptedException e) {
logger.error("开启时间错误"+new Date()+":"+e.getMessage());
}
logger.info("开启时间:"+new Date());
System.out.println("开启时间:"+new Date());
}
}
注意:
1.我为什么要使用 chmod 777命令呢?在有的机器上面,可能没有设置权限问题。这是你在linux下面执行shell脚本需要注意的问题。没有的话,就需要添加权限,就用chmod 777,否则在执行到Runtime.getRuntime().exec的时侯会出现Permission denied错误。
2.waitFor()这个也是必不可缺的,如果你需要执行多行命令的话,把waitFor()这个加上。