I have to schedule some tasks at some interval and have to kill the task which is taking more than specified time.
code:
public class ExecutorMain {
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(2);
scheduledExecutorService.scheduleAtFixedRate(new ShortTask(2), 0, 3, TimeUnit.SECONDS);
scheduledExecutorService.scheduleAtFixedRate(new LongTask(1), 0, 10, TimeUnit.SECONDS);
}
}
class ShortTask implements Runnable {
private int id;
ShortTask(int id) {
this.id = id;
}
public void run() {
try {
Thread.sleep(1000);
System.out.println("Short Task with id "+id+" executed by "+Thread.currentThread().getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class LongTask implements Runnable {
private int id;
LongTask(int id) {
this.id = id;
}
public void run() {
try {
Thread.sleep(6000);
System.out.println("Long Task with id "+id+" executed by "+Thread.currentThread().getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In the above example, i want to kill the task which is taking more than 5 secs(LongTask) without disturbing the execution of other tasks. what is the best way to achieve this?