I am working with threads, and decided to use the most modern API (java.util.concurrent package).
Here’s what I want to do (pseudocode):
//List of threads
private ScheduledExecutorService checkIns = Executors.newScheduledThreadPool(10);
//Runnable class
private class TestThread implements Runnable{
private int index = 0;
private long startTime = 0;
private long timeToExecute = 3000000;
public TestThread(int index){
this.index = index;
}
public void run(){
if(startTime == 0)
startTime = System.currentTimeMillis();
else if(startTime > (startTime+timeToExecute))
//End Thread
System.out.println("Execute thread with index->"+index);
}
}
//Cycle to create 3 threads
for(int i=0;i< 3; i++)
checkIns.scheduleWithFixedDelay(new TestThread(i+1),1, 3, TimeUnit.SECONDS);
I want to run a task on a certain date and repeat it until a certain amount of time. After the time has elapsed, the task ends. My only question is how to end with the thread?
Well, you can throw an exception from the task when it should no longer execute, but that’s fairly brutal Alternatives:
Of course the first version can be encapsulated into a somewhat more pleasant form – you could create a “SchedulingRunnable” which knows when it’s meant to run a subtask (provided to it) and how long for.