/*
 * Scone - The Web Enhancement Framework
 * Copyright (C) 2009 Harald Weinreich, Volkert Buchmann, Frank Wollenweber, Torsten Haß
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package  scone.util;


/**
 * a Thread for service tasks like cache cleaning.
 * The Thread runs a loop that will sleep for a specified 
 * interval and then execute the doService() method.
 * The Thread may be retired by calling the retire() method.
 */
public abstract class ServiceThread extends Thread {
    private int sleepTime;
    private boolean willRetire = false;

    /**
     * creates a new ServiceThread. 
     * 
     * @param sleepTime the sleep interval
     */
    public ServiceThread(int sleepTime) {
        this.sleepTime = sleepTime;
    }

    /**
     * the run method
     */
    public void run() {
        if (sleepTime > 0) {
            while (true) {
                try {
                    sleep(sleepTime);
                    doService();
                } catch (InterruptedException e) {
                    if (willRetire) {
                        cleanUp();
                        return;
                    }
                }
            }
        }
    }

    /**
     * retires the ServiceThread. 
     * Execution will be interrupted and the cleanUp() method
     * will be called.
     */
    public void retire() {
        willRetire = true;
        try {
            interrupt();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * overwrite this method to define the service task of the Thread.
     */
    public abstract void doService();

    /**
     * overwrite this method to define the clean up tasks for the end of the Thread
     */
    public abstract void cleanUp();
}

