I will be receiving an attribute and I want to run a job for that attribute for 1 hour – monitoring and logging things related to that attribute. After that one hour, the job will stop.
Is there a way to run a task, thread or a job for one hour given a id for that thread? As far as I know, the SchedulerExecutorService runs with a delay and after a certain interval. But how can I stop the job for that particular thread after one hour.
One more thing to note here is – there is a thread which will run for one hour and terminate. And there is another thread inside the one hour thread which will be doing some work every 5 minutes. So all in all I want a job to run for one hour and then inside that thread, another thread which will run every 5 minutes.
Kindly help.
class Task1 implements Runnable {
String abc;
private final ScheduledExecutorService monitorService;
private boolean isShutDown = false;
public Task1(String abc) {
this.abc = abc;
this.monitorService = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setNameFormat("checker-%s").build());
}
@Override
public void run()
{
Stopwatch stopwatch = Stopwatch.createStarted();
monitorService.scheduleAtFixedRate(new Task2(abc), 2, 300000, TimeUnit.MILLISECONDS);
long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
if(elapsed == 3600000) {
shutdownAndAwaitTermination(monitorService);
isShutDown = monitorService.isShutdown() || monitorService.isTerminated();
}
}
public boolean isShutDown()
{
return isShutDown;
}
}
public class Task2 implements Runnable //This should run every 5 minutes
{
private String abc;
public Task2(abc) {
this.abc = abc;
}
@Override
public void run()
{
System.out.println(abc);
}
}
Task1 task1 = new Task1("abc");
task1.run(); //This should run for 1 hour and terminate
Advertisement
Answer
The only proper way to terminate a thread is for a thread itself to exit the run() method. Do not stop, interrupt or kill the thread – read the documentation for explanation why.
Do something like this:
public void run() {
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime < 3600000) {
// ... do your stuff here ...
}
}