Search code examples
javaandroidandroid-studiohandlerjava-threads

how to run a thread for a specific time in android studio


I am using a thread to run my database connection checking I want this thread to run for a specific time , I tried using countdown Timer class ,but that didn't ,work any help please.


Solution

  • You can use an ExecutorService and do something like this:

    public class ExampleClass {
        public static void main(String[] args) throws Exception {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            Future<String> future = executor.submit(new DatabaseConnection());
    
            try {
                future.get(3, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                ...
            } catch (ExecutionException e) {
                ...
            } catch (TimeoutException e) {
                // do something in case of timeout
                future.cancel(true);
            }
    
            executor.shutdownNow();
        }
    }
    
    class DatabaseConnection implements Callable<String> {
        @Override
        public String call() throws Exception {
            while (!Thread.interrupted()) {
                // Perform your task here, e.g. connect to your database
            }
            return "Success";
        }
    }
    

    This way you perform a task on another thread with any timeout you want. In the above code snippet a timeout of three seconds is set.