Reputation: 2579
I am working on a simulation program in java, and we are finding that we need a lightweight java process to kick itself off at a certain (randomly generated) time, perform a few tasks, and then schedule the next task (randomly generated as well as generated from the results of the first task).
The program currently runs in a linux environment, but I would like to keep options open such that it could be run on OSX and Windows environments in the future.
How would I schedule these in java without using too much resources on the scheduling?
Upvotes: 2
Views: 1061
Reputation: 11087
As recommended in ScheduledThreadPoolExecutor
javadocs use it in favor of Timer
A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.
public class TaskTimer {
public static void main(String[] args) {
ScheduledExecutorService svc = Executors.newScheduledThreadPool(0);
svc.schedule(new Task(svc), 2, TimeUnit.SECONDS);
}
}
class Task implements Callable<Result> {
private ScheduledExecutorService svc;
public Task(ScheduledExecutorService svc) {
this.svc = svc;
}
@Override
public Result call() throws Exception {
Result result = compute();
Task t = nextTask(result);
svc.schedule(t, 2, TimeUnit.SECONDS);
return result;
}
private Task nextTask(Result result) {
return new Task(svc);
}
private Result compute() {
System.out.println("Computing Result");
return new Result();
}
}
class Result {
}
Upvotes: 3
Reputation: 2363
You can use a priority queue
essentially you put first task in to the priority queue
pop it
that in turns generates random tasks assign priority to each of those tasks
the ordering will happen naturally when you add them to the priority queue.
start popping based on how much time you need to wait if a particular tasks requires a particular time to wait.
Upvotes: 0
Reputation: 24651
For maximum portability let the java program run continuously and just do things at certain times using the standard java Timer
If you want persistent timers, that are resistant to crashes and restarts, and if you don't mind using a Java EE server such as Glassfish (I would recommend it even for a lightweight task), then you can use the persistent timers that are standard in Java EE.
Upvotes: 1