我正在尝试轮询服务器中的数据库并检查是否添加了任何新记录,如果有的话,我将使用新记录向 java 应用程序发送 http 请求。
这是 GET 请求:
public class PHPDataChecker implements Runnable {
public static String output;
public void run(){
try {
URL url = new URL("http://taxi.net/login.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我正在使用调度程序,这是代码:
public class Main {
private static boolean canStop=false;
public static void stopPHPDataChecker() {
canStop=true;
}
public static void runnner() {
// Setup a task for checking data and then schedule it
PHPDataChecker pdc = new PHPDataChecker();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> pdcHandle = scheduler.scheduleAtFixedRate(pdc, 0L, 10L, TimeUnit.MILLISECONDS);// Start schedule
scheduler.schedule(new Runnable() {
public void run() {
System.out.println(">> TRY TO STOP!!!");
pdcHandle.cancel(true);
Main.stopPHPDataChecker();
System.out.println("DONE");
}
}, 10L, TimeUnit.MILLISECONDS);
do {
if (canStop) {
scheduler.shutdown();
}
} while (!canStop);
System.out.println("END");
}
另外两个程序定期轮询它
运行Main.java:
public class RunMain implements Runnable {
public void run(){
Main m=new Main();
m.runnner();
}}
checkSchedule.java:
public class checkSchedule {
public static void main(String[] args) {
RunMain m = new RunMain();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> pdcHandle = scheduler.scheduleAtFixedRate(m, 0L, 10L, TimeUnit.SECONDS);
}
}
这不会正确轮询数据库编码有什么问题吗?
这是我在 nebeans IDE 中看到的输出
服务器输出 ....
{"return":"0"}
服务器输出 ....
{"return":"0"}试着停下来!!!
DONE
END
尝试停止!!!
DONE
END
尝试停止!!!
DONE
END
尝试停止!!!
DONE
END
尝试停止!!!
DONE
END
尝试停止!!!
DONE
END
尝试停止!!!
DONE
END
尝试停止!!!
DONE
END
尝试停止!!!
DONE
END
尝试停止!!!
完成
结束