Java发送请求 & SpringBoot定时任务
Java发送请求
处理中文字符要用URLEncoder.encode进行编码
public void sendRequest(String subUrl, String para) throws IOException {
URL url = new URL("http://localhost:5000/"+subUrl+para);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
System.out.println(content.toString());
}
sendRequest("textcnn_data_process","?zb_id="+zid+"&zh="+URLEncoder.encode(zh, "utf8"));
SpringBoot定时任务
新建一个task的package,再新建一个timerTask的类,别忘了加上@Component标注
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
@Component
public class timerTask {
@Resource
private ZhuanZhengService zhuanZhengService;
@Scheduled(cron = "0/6 * * * * ?") // 每6秒执行一次
private void timerInitFiles() throws IOException {
zhuanZhengService.initZhuanZhengs();
zhuanZhengService.getFiles();
zhuanZhengService.haveGetFiles();
}
@Scheduled(cron = "0 0/1 * * * ? ") // 每一分钟执行一次
private void trainModel() throws IOException {
zhuanZhengService.trainModel();
}
}
同时要在启动类上添加标注@EnableScheduling
@EnableScheduling
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
关于cron设置时间的语法规则,如果想快速生成,则参考使用这个网站:
https://cron.qqe2.com/
SpringBoot执行Linux命令
如果是简单命令(命令中不带有“|”、“<”、“>”等字符的命令)
直接使用Runtime.getRuntime().exec()方法
Process process = Runtime.getRuntime().exec("expect /home/auto/code_main/sendModel.exp "+zid);
如果是复杂命令(命令中带有“|”、“<”、“>”等字符)
cmd中的第三个指令中的内容可以替换成其他指令
private int getFreeGPU() throws IOException {
List<Integer> memGpus = new ArrayList<>();
String[] cmd = {
"/bin/sh", "-c", "nvidia-smi -q -d Memory |grep -A4 GPU|grep Free" }; // 第三个引号中的内容可以替换成你的指令
Process process = new ProcessBuilder(cmd).start();
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split("\\s+");
int number = Integer.parseInt(parts[3]);
memGpus.add(number);
}
return memGpus.size();
}