001 /**
002 * Jetrix TetriNET Server
003 * Copyright (C) 2001-2004 Emmanuel Bourg
004 *
005 * This program is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU General Public License
007 * as published by the Free Software Foundation; either version 2
008 * of the License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013 * GNU General Public License for more details.
014 *
015 * You should have received a copy of the GNU General Public License
016 * along with this program; if not, write to the Free Software
017 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
018 */
019
020 package net.jetrix.services;
021
022 import java.util.Timer;
023 import java.util.TimerTask;
024
025 /**
026 * A service running a task at a fixed rate. Services based on ScheduledService
027 * expect a <tt>delay</tt> parameter for the delay in milliseconds before the
028 * task is first executed, and a <tt>period</tt> parameter for the time in
029 * milliseconds between successive executions of the task.
030 *
031 * @author Emmanuel Bourg
032 * @version $Revision: 794 $, $Date: 2009-02-17 20:08:39 +0100 (Tue, 17 Feb 2009) $
033 * @since 0.2
034 */
035 public abstract class ScheduledService extends AbstractService
036 {
037 private long period;
038 private long delay;
039 private Timer timer;
040
041 /**
042 * Initialization performed before the timer is started.
043 */
044 protected void init() { }
045
046 public void start()
047 {
048 if (!isRunning())
049 {
050 init();
051
052 TimerTask task = new TimerTask()
053 {
054 public void run()
055 {
056 ScheduledService.this.run();
057 }
058 };
059
060 // start the timer
061 timer = new Timer();
062 timer.schedule(task, delay, period);
063 }
064 }
065
066 public void stop()
067 {
068 // stop the timer
069 if (isRunning())
070 {
071 timer.cancel();
072 timer = null;
073 }
074 }
075
076 /**
077 * Check is the service is running.
078 */
079 public boolean isRunning()
080 {
081 return timer != null;
082 }
083
084 /**
085 * Execute the task
086 */
087 protected abstract void run();
088
089 /**
090 * Get the time in milliseconds between successive executions of the task.
091 */
092 public long getPeriod()
093 {
094 return period;
095 }
096
097 /**
098 * Set the time in milliseconds between successive executions of the task.
099 */
100 public void setPeriod(long period)
101 {
102 this.period = period;
103 }
104
105 /**
106 * Get the delay in milliseconds before the task is first executed.
107 */
108 public long getDelay()
109 {
110 return delay;
111 }
112
113 /**
114 * Set the delay in milliseconds before the task is first executed.
115 */
116 public void setDelay(long delay)
117 {
118 this.delay = delay;
119 }
120
121 }