3

I am trying to implement a ScheduledExecutorService thread that loops every second, but as of right now it only loops once.

My question is how do I set it up so that it loops periodically instead of one iteration?

Also,how do I pass the connection pool into the thread so that I can query a database every iteration? Any help is much appreciated.

public static void main(String[] args) throws InterruptedException {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    AdminManager frame = new AdminManager();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        BoneCP connectionPool = null;
        Connection connection = null;

        try {
            // load the database driver (make sure this is in your classpath!)
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        try {
            // setup the connection pool
            BoneCPConfig config = new BoneCPConfig();
            config.setJdbcUrl("jdbc:mysql://192.0.0.1:3306/database"); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb
            config.setUsername("root"); 
            config.setPassword("");
            connectionPool = new BoneCP(config); // setup the connection pool

            connection = connectionPool.getConnection(); // fetch a connection

            if (connection != null){
                System.out.println("Connection successful!");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.schedule(new Runnable(){
            @Override
            public void run(){
                System.out.println("Working ... ");

            }
        }, 1, TimeUnit.SECONDS);

        //connectionPool.shutdown(); // shutdown connection pool.
}
scriptdiddy
  • 1,207
  • 3
  • 17
  • 31

1 Answers1

3

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html

there's a scheduleAtFixedRate method. To pass something in to a anonymous class it needs to be declared final. And it needs to be in the same scope.

Also the code you have now is closing the connection, if you intend on passing it to another thread you need to keep it open.

!Edit some sample code

public class Whatever {
    public static void main(String[] args) throws Exception {
        // ... do your frame thing

        loadDataBaseDriver();
        BoneCP connectionPool = createConnectionPool();

        try {
            final Connection connection = connectionPool.getConnection();
            ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();

            exec.scheduleAtFixedRate(new Runnable(){
                @Override
                public void run(){
                    System.out.println("Working ... ");

                    // use connection
                }
            }, 0, 1, TimeUnit.SECONDS);
        } catch (SQLException e) {
          // do whatever
        }
    }

    public static BoneCP createConnectionPool() throws SQLException {
        BoneCPConfig config = new BoneCPConfig();
        config.setJdbcUrl("jdbc:mysql://192.0.0.1:3306/database"); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb
        config.setUsername("root"); 
        config.setPassword("");
        connectionPool = new BoneCP(config);
        return connectionPool;
    }

    public static void loadDataBaseDriver() {
        try {
            // load the database driver (make sure this is in your classpath!)
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

}

I don't know the signatures of the methods you are calling so the errors might be wrong

megakorre
  • 2,213
  • 16
  • 23
  • Okay. Thank you for showing me scheduleAtFixed Rate method. I attempted to declare the connection final and it gave me the following error ... Exception in thread "main" java.lang.Error: Unresolved compilation problems: The final local variable connection cannot be assigned. It must be blank and not using a compound assignment Unhandled exception type SQLException Unhandled exception type SQLException – scriptdiddy Jul 07 '12 at 23:32
  • Why? Why do you get the Connection outside the thread. Just get it IN the thread, a nice local confined variable (Connections are NOT threadsafe anyway). Make the ConnectionPool final and then use it to get the connection INSIDE the thread. – MJB Jul 08 '12 at 07:32