2014-02-20 111 views
-3

我在列表中有一组服务器。我想每隔30分钟ping这些服务器。我可以如何实现这一点。它是一个带有java代码的jsp程序。每30分钟自动Ping一台外部服务器

+0

除非你使用本地代码你不能做一个“真正平”(即ICMP回应请求)的Java或一个外部过程... – fge

+1

使用线程不能我们这样做 – csrocks

+1

这个问题似乎是脱离主题,因为OP要求我们为他/她编写代码。 –

回答

1

这个代码将每30分钟后,再执行对ping命令给定的IP

public boolean ping(String ip) throws IOException, InterruptedException extends TimerTask { 
    public void run{  
    boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win"); 

      ProcessBuilder processBuilder = new ProcessBuilder("ping", isWindows? "-n" : "-c", "1", ip`enter code here`); 
      Process proc = processBuilder.start(); 
      BufferedReader in = 
     new BufferedReader(
     new InputStreamReader(proc.getInputStream())); 
     while (true) { 
     String line = in.readLine(); 
     if (line == null) 
     break; 
     if(line.contains("Destination host unreachable")||line.contains("Request timed out")){ 

      return false; 
      } 
     } 

      return true; 
} 

     } 
// And From your main() method or any other method 
Timer timer = new Timer(); 
timer.schedule(new ping(ip), 0, (60*30*1000)); 
+0

我必须手动运行ping ... o此代码会在30分钟后自动ping通 – csrocks

+0

上面的代码是手动的,可以ping到服务器,但可能会在30分钟后通过线程执行。 – swapnil7

+0

如何使用线程编写代码 – csrocks