I want a task to run at scheduled interval and timeout if it does not complete in required time and continue further iteration.
I have gone through the following answers, but it doesn't address my problem..
How do you kill a Thread in Java?
ExecutorService that interrupts tasks after a timeout
Consider the following case
    BasicThreadFactory collectionFactory = new BasicThreadFactory.Builder()
            .namingPattern("CollectionExecutor-%d")
            .build();
    // thread pool size is set 2
    // 1-for scheduler thread which runs task and tracks timeout
    // 2-for task itself
    ScheduledExecutorService collectionExecuter = 
            Executors.newScheduledThreadPool(2, collectionFactory);
    // fires collection every minute and if it is in between execution during
    // scheduled time then waits for completion and executes immediately
    // after it
    //my task:
    Runnable runnable= new Runnable() {
        @Override
            public void run() {
        try {
            System.out.println("Executed started");
            Thread.sleep(2000);
            System.out.println("Executed after .get method call.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(20000);
            System.out.println("Executed even after .cancel method " +
                    "call (I want this to avoid this.)");
        } catch (Exception e) {
            e.printStackTrace();
        }               
    }
};
Above task should run with an interval of 3 sec and stop if it takes more than 1 sec...Consider It is not possible to have complete task in single try catch block, now how could I stop the task to wait further in next sleep(20000) and continue with next iteration.
    collectionExecuter.scheduleAtFixedRate(new Runnable() {//scheduler thread
        @Override
        public void run() {
            try {
                Future<?> future = collectionExecuter.submit(runnable);
                try {
                    future.get(1, TimeUnit.SECONDS);
                } catch (Exception e) {
                    future.cancel(true);
                    System.out.println("Collection thread did not " +
                           "completed in 1 Sec.Thread Interrupted");
                }
            } catch (Exception e) {
                System.out.println("Unable to start Collection Thread");
            }
        }
    }, 0, 3, TimeUnit.SECONDS);
}
 
    