From 382d5ab7e938f769ffb64f0adc36ae05ff905fc5 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 8 Jul 2007 22:52:58 +0000 Subject: [PATCH] add Cron darcs-hash:20070708225258-5007d-d4dc34bde6f5d1cfe5636dbaadabd9fd6ac16899.gz --- src/org/ibex/util/Cron.java | 69 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/org/ibex/util/Cron.java 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(); + } + } + } + } +} + -- 1.7.10.4