From ce24c79d8a7100ad9801a580fe91ad6414dfc45b Mon Sep 17 00:00:00 2001 From: Harald Wolff Date: Wed, 8 Jun 2016 23:33:43 +0200 Subject: [PATCH] Scheduler --- src/org/hwo/scheduler/Scheduler.java | 106 +++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 src/org/hwo/scheduler/Scheduler.java diff --git a/src/org/hwo/scheduler/Scheduler.java b/src/org/hwo/scheduler/Scheduler.java new file mode 100644 index 0000000..afc8940 --- /dev/null +++ b/src/org/hwo/scheduler/Scheduler.java @@ -0,0 +1,106 @@ +package org.hwo.scheduler; + +import java.util.LinkedList; +import java.util.List; + +public class Scheduler extends Thread{ + + private List schedulerTasks; + private boolean exit; + + public Scheduler(){ + schedulerTasks = new LinkedList(); + 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; + } + + + } +} + +