定时访问url,判断服务是否正常
作者:互联网
package com.epson.esl.rms;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TestUrl {
public static void main(String[] args) {
timer1();
}
public static void timer1() {
Timer nTimer = new Timer();
nTimer.schedule(new TimerTask() {
@Override
public void run() {
testUrlWithTimeOut("http://127.0.0.1:8888", 20000); //超时时间 20秒
}
},0, 300000); // 0代表立即执行一次task,然后每隔300秒执行一次task
}
public static void testUrlWithTimeOut(String urlString, int timeOutMillSeconds) {
URL url;
try {
url = new URL(urlString);
URLConnection co = url.openConnection();
co.setConnectTimeout(timeOutMillSeconds); //设置超时时间,否则时间长没有响应会一直等
co.connect();
System.out.println("连接可用 <" + new Date() + ">" + "("+ urlString + ")");
} catch (Exception e1) {
System.out.println("连接不可用! <" + new Date() + ">" + "("+ urlString + ")");
url = null;
}
}
}
标签:java,url,void,urlString,访问,import,定时,public 来源: https://blog.csdn.net/qq3892997/article/details/117738059