1 /*********************************************************************
2 Copyright 2012, Ralph Ronnquist.
4 This file is part of GORITE.
6 GORITE is free software: you can redistribute it and/or modify it
7 under the terms of the Lesser GNU General Public License as published
8 by the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GORITE is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
14 License for more details.
16 You should have received a copy of the Lesser GNU General Public
17 License along with GORITE. If not, see <http://www.gnu.org/licenses/>.
18 **********************************************************************/
20 package com.intendico.gorite.addon;
22 import com.intendico.gorite.Data;
23 import java.util.Observable;
24 import java.util.Timer;
25 import java.util.TimerTask;
28 * This class defines an Observable that schedules itself for issuing
29 * a notfication to Observers at a future time.
31 public class TimeTrigger extends Observable {
34 * Utility method to establish a TimeTrigger as a {@link Data}
35 * element value, and use as execution trigger after the given
36 * delay. The indicated {@link com.intendico.gorite.Data.Element
37 * Data.Element} should be unset initially, to be set by this
38 * method to a TimeTrigger for the given delay. Upon subsequent
39 * calls, the TimeTrigger is rescheduled until its deadline has
40 * passed, at which time the given {@link
41 * com.intendico.gorite.Data.Element Data.Element} is forgotten.
42 * @return true if a trigger has been set and false otherwise
44 public static boolean isPending(Data data,String element,long delay) {
45 TimeTrigger tt = (TimeTrigger) data.getValue( element );
47 tt = new TimeTrigger( delay );
48 data.setValue( element, tt );
49 data.setTrigger( tt );
51 if ( tt.reschedule() )
53 data.forget( element );
58 * A global {@link Timer} for scheduling future events on.
60 public static Timer timer = new Timer( true );
63 * The deadline time for this TimeTrigger.
68 * Constructor for a given future time.
70 public TimeTrigger(long delay) {
71 deadline = System.currentTimeMillis() + delay;
75 * Reset for triggering at a new future time.
77 public void reset(long delay) {
78 deadline = System.currentTimeMillis() + delay;
82 * This method tests whether the trigger time is reached or not,
83 * and if not, it sets up a {@link TimerTask} for notifying
84 * observers when the trigger time is reached.
86 public boolean reschedule() {
87 long delay = deadline - System.currentTimeMillis();
90 timer.schedule( new TimerTask() {
93 notifyObservers( this );