Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package pl.cornersoft.test;
- import java.sql.*;
- public class NotificationTest {
- public static void main(String args[]) throws Exception {
- Class.forName("org.postgresql.Driver");
- String url = "jdbc:postgresql://192.168.23.159:5432/michal";
- Connection lConn = DriverManager.getConnection(url,"michal","123");
- Listener listener = new Listener(lConn);
- listener.start();
- }
- }
- class Listener extends Thread {
- private Connection conn;
- private org.postgresql.PGConnection pgconn;
- Listener(Connection conn) throws SQLException {
- this.conn = conn;
- this.pgconn = (org.postgresql.PGConnection)conn;
- Statement stmt = conn.createStatement();
- stmt.execute("LISTEN virt");
- stmt.close();
- }
- public void run() {
- while (true) {
- try {
- Thread.currentThread().sleep(1000);
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("SELECT 1");
- rs.close();
- stmt.close();
- org.postgresql.PGNotification notifications[] = pgconn.getNotifications();
- if (notifications != null) {
- for (int i=0; i<notifications.length; i++) {
- System.out.println("Got notification: " + notifications[i].getName());
- System.out.println("Got notification: " + notifications[i].getParameter());
- System.out.println("Got notification: " + notifications[i].getPID());
- System.out.println("Got notification: " + notifications[i].getClass().getName());
- }
- }
- // wait a while before checking again for new
- // notifications
- Thread.sleep(500);
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- } catch (InterruptedException ie) {
- ie.printStackTrace();
- }
- }
- }
- }
- /*
- class Notifier extends Thread {
- private Connection conn;
- public Notifier(Connection conn) {
- this.conn = conn;
- }
- public void run() {
- while (true) {
- try {
- Statement stmt = conn.createStatement();
- stmt.execute("NOTIFY mymessage");
- stmt.close();
- Thread.sleep(2000);
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- } catch (InterruptedException ie) {
- ie.printStackTrace();
- }
- }
- }
- }*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement