ScheduledExecutorService only loops once

前端 未结 1 1045
野的像风
野的像风 2021-01-14 11:09

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

相关标签:
1条回答
  • 2021-01-14 11:29

    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

    0 讨论(0)
提交回复
热议问题