0

使用下面显示的编码,我设法使用 php 从服务器中的 sql 数据库中检索数据。我需要定期检查数据库以查看是否添加了任何新数据,如果有,我需要将它们检索到我的 java 应用程序中。我正在使用 netbeans IDE 我该怎么做?

try {
    URL url = new URL("http://taxi.com/login.php?param=10");
    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())));

    String output;
    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();

  }

}
4

1 回答 1

0

在此解决方案中,我假设您至少使用Java 5
假设您想每 5 分钟检查一次新数据并在 25 分钟后终止。
你会这样做:

PHPDataChecker.java

public class PHPDataChecker implements Runnable {
    public void run() {
       // Paste here all the code in your question
    }
}

主.java

public class Main {
    private static boolean canStop=false;

    private static void stopPHPDataChecker() {
        canStop=true;
    }

    public static void main(String[] args) {
        // 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, 5L, TimeUnit.MINUTES);// Start pooling

        // Setup a new task to kill the polling after 25 minutes
        scheduler.schedule(new Runnable() {

            public void run() {
                System.out.println(">> TRY TO STOP!!!");
                pdcHandle.cancel(true);
                Main.stopPHPDataChecker();
                System.out.println("DONE");
            }

        }, 25L, TimeUnit.MINUTES);

        // Actively wait stop condition (canStop)
        do {
            if (canStop) {
                scheduler.shutdown();
            }
        } while (!canStop);

        System.out.println("END");
    }
}
于 2012-09-18T08:12:50.877 回答