Scheduler

thobaben_serialize
Harald Wolff 2016-06-08 23:33:43 +02:00
parent d6bfabf02a
commit ce24c79d8a
1 changed files with 106 additions and 0 deletions

View File

@ -0,0 +1,106 @@
package org.hwo.scheduler;
import java.util.LinkedList;
import java.util.List;
public class Scheduler extends Thread{
private List<SchedulerTask> schedulerTasks;
private boolean exit;
public Scheduler(){
schedulerTasks = new LinkedList<Scheduler.SchedulerTask>();
exit = false;
start();
}
public synchronized void schedule(Runnable runnable,int intervall,boolean fixedIntervall){
SchedulerTask task = new SchedulerTask(runnable, fixedIntervall, intervall);
this.schedulerTasks.add(task);
this.notify();
}
public synchronized void shutdown(){
this.exit = true;
}
@Override
public void run() {
while (!exit){
synchronized (this) {
try {
this.wait(getWaitTime());
} catch (InterruptedException e) {
}
checkScheduledTasks();
}
}
}
private void checkScheduledTasks(){
long currentTime = System.currentTimeMillis();
for (SchedulerTask task: schedulerTasks){
if (task.nextStart <= currentTime){
if (task.fixedIntervall)
task.nextStart += task.intervall;
else
task.nextStart = currentTime + task.intervall;
try {
task.runnable.run();
} catch (Exception e){
System.err.println("Scheduler caught runnable's Exception!");
e.printStackTrace();
}
}
}
}
private int getWaitTime(){
long currentTime = System.currentTimeMillis();
long target = currentTime + 1000;
for (SchedulerTask task: schedulerTasks){
if (task.nextStart <= target)
target = task.nextStart;
}
int w = (int)(target-currentTime);
if (w < 1)
return 1;
return w;
}
class SchedulerTask {
private int intervall;
private Long nextStart;
private boolean fixedIntervall;
private Runnable runnable;
public SchedulerTask(Runnable runnable,boolean fixedIntervall,int intervall) {
this.intervall = intervall;
this.fixedIntervall = fixedIntervall;
this.runnable = runnable;
this.nextStart = System.currentTimeMillis() + this.intervall;
}
}
}