X-Git-Url: http://git.megacz.com/?p=org.ibex.util.git;a=blobdiff_plain;f=src%2Forg%2Fibex%2Futil%2FCron.java;fp=src%2Forg%2Fibex%2Futil%2FCron.java;h=6dd36882268bb62addba863c2ee783b83425d624;hp=0000000000000000000000000000000000000000;hb=382d5ab7e938f769ffb64f0adc36ae05ff905fc5;hpb=55f0d8b05ba8b6ef036f31eb899813d8eaa4bc5a diff --git a/src/org/ibex/util/Cron.java b/src/org/ibex/util/Cron.java new file mode 100644 index 0000000..6dd3688 --- /dev/null +++ b/src/org/ibex/util/Cron.java @@ -0,0 +1,69 @@ +// Copyright 2007 the Contributors, as shown in the revision logs. +// Licensed under the Apache Public Source License 2.0 ("the License"). +// You may not use this file except in compliance with the License. + +package org.ibex.util; + +import java.io.*; + +// FEATURE: auto-rescheduling +// (currently cronjobs must manually reschedule themselves) + +/** + * A manager for periodic tasks ("cron jobs") + */ +public final class Cron extends ImmortalThread { + + private static ThreadPool threadPool; + + private Vec tasks = new Vec(); + private long wakeup = 0; + + public Cron(ThreadPool threadPool) { + super(0); + this.threadPool = threadPool; + start(); + } + + public synchronized void cycle() { + try { + long now = System.currentTimeMillis(); + if (wakeup == 0) wait(); + else if (wakeup > now) wait(wakeup - now); + } catch (Exception e) { Log.error(this, e); } + wakeup = 0; + long now = System.currentTimeMillis(); + // FIXME: linear scan is inefficient + for(int i=0; i t.when) + wakeup = t.when; + } + } + } + + public void executeLater(long howLongFromNow, Runnable runnable) { + new Task(runnable, System.currentTimeMillis()+howLongFromNow); + } + + private class Task { + final Runnable runnable; + final long when; + public Task(Runnable runnable, long when) { + this.runnable = runnable; + this.when = when; + synchronized(Cron.this) { + tasks.add(this); + if (wakeup == 0 || wakeup > when) { + wakeup = this.when; + Cron.this.notify(); + } + } + } + } +} +