If you run your task in a thread, you can keep a reference to the Future object of the task and set a timeout. Something like that :
Future<?> future = executor.submit(new customTask()));
try {
future .get(timeout, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
// The timeout exception is thrown when the get times out. Handle your stop logic here
}
You might want to handle the InterruptedException, ExecutionException and TimeoutException separately.
You can also call the .cancel() method on the Future object when your stop timer expires, but I recall reading somewhere that it is not recommanded