Search code examples
javamultithreadingconcurrencyrunnable

How to initialise Thread to sleep


i am trying to write a method that pings my database every hour. In doing so I am having some difficulties in sleeping the Thread is it might not have been initialised

private void pingServer(){
    final Thread serverPing = new Thread(new Runnable() {
        @Override
        public void run() {
            Connection conn = null;
            try {
                conn = source.getConnection();
                while(conn.isValid(3600)){
                    //no need to do anything as conn.isValid does the ping
                    serverPing.sleep(3600000);
                }
            } catch (SQLException | InterruptedException e) {}
            finally{
                closeConnection(conn);
            }
        }
    });
    serverPing.setDaemon(true);
    serverPing.start();
}

How can i modify this code to initialise it correctly?

Thanks


Solution

  • To sleep, just use Thread.sleep(3600000);

    Yet, you should use a ScheduledExecutorService for this kind of tasks:

    ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    ses.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            try(Connection conn = source.getConnection()){
                if(!conn.isValid(3600)){
                    // do something if the connection is invalid
                }
            }
        }
    }, 0, 1, TimeUnit.HOURS);