You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@turbine.apache.org by qu...@apache.org on 2003/01/20 22:52:14 UTC

cvs commit: jakarta-turbine-2/src/java/org/apache/turbine/services/schedule SchedulerTool.java JobEntry.java JobQueue.java ScheduleService.java TurbineNonPersistentSchedulerService.java TurbineScheduler.java TurbineSchedulerService.java WorkerThread.java

quintonm    2003/01/20 13:52:14

  Modified:    src/java/org/apache/turbine/services/schedule JobEntry.java
                        JobQueue.java ScheduleService.java
                        TurbineNonPersistentSchedulerService.java
                        TurbineScheduler.java TurbineSchedulerService.java
                        WorkerThread.java
  Added:       src/java/org/apache/turbine/services/schedule
                        SchedulerTool.java
  Log:
  Backport of scheduler service from Fulcrum + enhancements
  - TurbineException is thrown instead of Exception
  - Uses Torque generated OM objects
  - Scheduler can be enabled/disabled after Turbine is initialized
  - fixed bug preventing change of a jobEntry from being recognized by the scheduler.
  - Added a new pull tool for accessing the scheduler service from a Velocity template
  
  Revision  Changes    Path
  1.9       +161 -424  jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/JobEntry.java
  
  Index: JobEntry.java
  ===================================================================
  RCS file: /home/cvs/jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/JobEntry.java,v
  retrieving revision 1.8
  retrieving revision 1.9
  diff -u -r1.8 -r1.9
  --- JobEntry.java	11 Jul 2002 07:34:30 -0000	1.8
  +++ JobEntry.java	20 Jan 2003 21:52:13 -0000	1.9
  @@ -54,51 +54,30 @@
    * <http://www.apache.org/>.
    */
   
  -import java.sql.Connection;
   import java.util.Calendar;
   import java.util.Date;
  -import java.util.Hashtable;
  -import org.apache.torque.om.BaseObject;
  -import org.apache.torque.om.NumberKey;
  -import org.apache.torque.util.Criteria;
  +
  +import org.apache.turbine.util.TurbineException;
   
   /**
    * This is a wrapper for a scheduled job.  It is modeled after the
    * Unix scheduler cron.
    *
    * @author <a href="mailto:mbryson@mont.mindspring.com">Dave Bryson</a>
  + * @author <a href="mailto:quintonm@bellsouth.net">Quinton McCombs</a>
    * @version $Id$
    */
  -public class JobEntry extends BaseObject
  -    implements Comparable
  +public class JobEntry
  +        extends BaseJobEntry
  +        implements Comparable
   {
  -    /** Valid entry ( 0-60 ). **/
  -    private int second = -1;
  -
  -    /** Valid entry ( 0-59 ). **/
  -    private int minute = -1;
  -
  -    /** Valid entry ( 0-23 ). **/
  -    private int hour = -1;
  -
  -    /** Valid entry ( 1-7 ). **/
  -    private int weekday = -1;
  -
  -    /** Valid entry ( 1-31 ). **/
  -    private int day_of_month = -1;
   
  -    /** The Task to perform. **/
  -    private String task = null;
  +    /** indicates if job is currently running */
  +    private boolean jobIsActive = false;
   
       /** Next runtime. **/
       private long runtime = 0;
   
  -    /** E-mail address to send notification of job run. **/
  -    private String email = "";
  -
  -    /** indicates if job is currently running */
  -    private boolean jobIsActive = false;
  -
       /** schedule types **/
       private static final int SECOND = 0;
       private static final int MINUTE = 1;
  @@ -106,11 +85,8 @@
       private static final int DAY_OF_MONTH = 3;
       private static final int DAILY = 4;
   
  -    /** Storage for additional properties */
  -    private Hashtable jobProp = null;
  -
       /**
  -     * Default Constructor
  +     * default constructor
        */
       public JobEntry()
       {
  @@ -145,7 +121,7 @@
        * @param wd Value for entry "week days".
        * @param day_mo Value for entry "month days".
        * @param task Task to execute.
  -     * @exception Exception, a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public JobEntry(int sec,
                       int min,
  @@ -153,361 +129,194 @@
                       int wd,
                       int day_mo,
                       String task)
  -        throws Exception
  +            throws TurbineException
       {
  -        if ( task == null || task.length() == 0 )
  -            throw new Exception("Error in JobEntry. Bad Job parameter. Task not set.");
  +        if(task == null || task.length() == 0)
  +        {
  +            throw new TurbineException("Error in JobEntry. " +
  +                    "Bad Job parameter. Task not set.");
  +        }
   
  -        this.second = sec;
  -        this.minute = min;
  -        this.hour = hour;
  -        this.weekday = wd;
  -        this.day_of_month = day_mo;
  -        this.task = task;
  +        setSecond(sec);
  +        setMinute(min);
  +        setHour(hour);
  +        setWeekDay(wd);
  +        setDayOfMonth(day_mo);
  +        setTask(task);
   
           calcRunTime();
       }
   
  -
       /**
  -     * Calculate how long before the next runtime.<br>
  -     *
  -     * The runtime determines it's position in the job queue.
  -     * Here's the logic:<br>
  -     *
  -     * 1. Create a date the represents when this job is to run.<br>
  -     *
  -     * 2. If this date has expired, them "roll" appropriate date
  -     * fields forward to the next date.<br>
  -     *
  -     * 3. Calculate the diff in time between the current time and the
  -     * next run time.<br>
  +     * Used for ordering Jobentries
  +     * Note: this comparator imposes orderings that are inconsistent with
  +     * equals.
        *
  -     * @exception Exception, a generic exception.
  +     * @param je The first <code>JobEntry</code> object.
  +     * @return An <code>int</code> indicating the result of the comparison.
        */
  -    public void calcRunTime()
  -        throws Exception
  +    public int compareTo(Object je)
       {
  -        Calendar schedrun = Calendar.getInstance();
  -        Calendar now = Calendar.getInstance();
  -
  -        switch( evaluateJobType() )
  +        int result = -1;
  +        if(je instanceof JobEntry)
           {
  -        case 0:
  -            // SECOND (every so many seconds...)
  -            schedrun.add (Calendar.SECOND,second);
  -            runtime = schedrun.getTime().getTime();
  -            break;
  -        case 1:
  -            // MINUTE (every so many minutes...)
  -            schedrun.add (Calendar.SECOND,second);
  -            schedrun.add(Calendar.MINUTE,minute);
  -            runtime = schedrun.getTime().getTime();
  -            break;
  -
  -        case 2:
  -            // WEEKDAY (day of the week)
  -            schedrun.add (Calendar.SECOND,second);
  -            schedrun.set(Calendar.MINUTE,minute);
  -            schedrun.set(Calendar.HOUR_OF_DAY,hour);
  -            schedrun.set(Calendar.DAY_OF_WEEK,weekday);
  -
  -            if ( now.before(schedrun) )
  -            {
  -                // Scheduled time has NOT expired.
  -                runtime = schedrun.getTime().getTime();
  -            }
  -            else
  -            {
  -                // Scheduled time has expired; roll to the next week.
  -                schedrun.add(Calendar.DAY_OF_WEEK,7);
  -                runtime = schedrun.getTime().getTime();
  -            }
  -            break;
  -
  -        case 3:
  -            // DAY_OF_MONTH (date of the month)
  -            schedrun.add (Calendar.SECOND,second);
  -            schedrun.set(Calendar.MINUTE,minute);
  -            schedrun.set(Calendar.HOUR_OF_DAY,hour);
  -            schedrun.set(Calendar.DAY_OF_MONTH,day_of_month);
  -
  -            if ( now.before(schedrun) )
  -            {
  -                // Scheduled time has NOT expired.
  -                runtime = schedrun.getTime().getTime();
  -            }
  -            else
  -            {
  -                // Scheduled time has expired; roll to the next month.
  -                schedrun.add(Calendar.MONTH,1);
  -                runtime = schedrun.getTime().getTime();
  -            }
  -            break;
  -
  -        case 4:
  -            // DAILY (certain hour:minutes of the day)
  -            schedrun.add (Calendar.SECOND,second);
  -            schedrun.set(Calendar.MINUTE,minute);
  -            schedrun.set(Calendar.HOUR_OF_DAY,hour);
  -
  -            // Scheduled time has NOT expired.
  -            if ( now.before(schedrun) )
  -            {
  -                runtime = schedrun.getTime().getTime();
  -            }
  -            else
  -            {
  -                // Scheduled time has expired; roll forward 24 hours.
  -                schedrun.add(Calendar.HOUR_OF_DAY,24);
  -                runtime = schedrun.getTime().getTime();
  -            }
  -            break;
  -
  -        default:
  -            // Do nothing.
  +            result = getJobId() - ((JobEntry) je).getJobId();
           }
  +        return result;
       }
   
       /**
  -     * Get the next runtime for this job as a long.
  +     * Sets whether the job is running.
        *
  -     * @return The next run time as a long.
  +     * @param isActive Whether the job is running.
        */
  -    public long getNextRuntime()
  +    public void setActive(boolean isActive)
       {
  -        return runtime;
  +        jobIsActive = isActive;
       }
   
       /**
  -     * Get the next runtime for this job as a String.
  +     * Check to see if job is currently active/running
        *
  -     * @return The next run time as a String.
  +     * @return true if job is currently geing run by the
  +     *  workerthread, otherwise false
        */
  -    public String getNextRunAsString()
  +    public boolean isActive()
       {
  -        return new Date(runtime).toString();
  +        return jobIsActive;
       }
   
       /**
  -     * The address to send mail notifications to.  This just holds the
  -     * address.  The ScheduledJob should handle actually sending the
  -     * mail.
  +     * Get the next runtime for this job as a long.
        *
  -     * @param mail The email address.
  +     * @return The next run time as a long.
        */
  -    public void setEmail(String mail)
  +    public long getNextRuntime()
       {
  -        this.email = mail;
  -        setModified(true);
  +        return runtime;
       }
   
       /**
  -     * Return the e-mail address for notification.
  +     * Gets the next runtime as a date
        *
  -     * @return The email address.
  +     * @return Next run date
        */
  -    public String getEmail()
  +    public Date getNextRunDate()
       {
  -        if ( email == null || email.length() == 0 )
  -        {
  -            return "not set";
  -        }
  -        else
  -        {
  -            return email;
  -        }
  +        return new Date(runtime);
       }
   
       /**
  -     * Return the task for this job.  A task name is the Class name of
  -     * the ScheduledJob created by the programmer.
  +     * Get the next runtime for this job as a String.
        *
  -     * @return A String with the name of the scheduled job.
  +     * @return The next run time as a String.
        */
  -    public String getTask()
  +    public String getNextRunAsString()
       {
  -        return task;
  +        return getNextRunDate().toString();
       }
   
       /**
  -     * Set the task name for this job.  A task name is the Class name
  -     * of the ScheduledJob created by the programmer.
  +     * Calculate how long before the next runtime.<br>
        *
  -     * @param task A String with the name of the job.
  -     */
  -    public void setTask(String task)
  -    {
  -        this.task = task;
  -        setModified(true);
  -    }
  -
  -    /**
  -     * Get the value of second.
  +     * The runtime determines it's position in the job queue.
  +     * Here's the logic:<br>
        *
  -     * @return Value of second.
  -     */
  -    public int getSecond()
  -    {
  -        return second;
  -    }
  -
  -    /**
  -     * Set the value of second.
  +     * 1. Create a date the represents when this job is to run.<br>
        *
  -     * @param v Value to assign to second.
  -     */
  -    public void setSecond(int v)
  -    {
  -        this.second = v;
  -        setModified(true);
  -    }
  -
  -
  -    /**
  -     * Get the value of minute.
  +     * 2. If this date has expired, them "roll" appropriate date
  +     * fields forward to the next date.<br>
        *
  -     * @return Value of minute.
  -     */
  -    public int getMinute()
  -    {
  -        return minute;
  -    }
  -
  -    /**
  -     * Set the value of minute.
  +     * 3. Calculate the diff in time between the current time and the
  +     * next run time.<br>
        *
  -     * @param v Value to assign to minute.
  +     * @exception TurbineException a generic exception.
        */
  -    public void setMinute(int v)
  +    public void calcRunTime()
  +            throws TurbineException
       {
  -        this.minute = v;
  -        setModified(true);
  -    }
  +        Calendar schedrun = Calendar.getInstance();
  +        Calendar now = Calendar.getInstance();
   
  -    /**
  -     * Get the value of hour.
  -     *
  -     * @return Value of hour.
  -     */
  -    public int getHour()
  -    {
  -        return hour;
  -    }
  +        switch(evaluateJobType())
  +        {
  +            case SECOND:
  +                // SECOND (every so many seconds...)
  +                schedrun.add(Calendar.SECOND, getSecond());
  +                runtime = schedrun.getTime().getTime();
  +                break;
   
  -    /**
  -     * Set the value of hour.
  -     *
  -     * @param v Value to assign to hour.
  -     */
  -    public void setHour(int v)
  -    {
  -        this.hour = v;
  -        setModified(true);
  -    }
  +            case MINUTE:
  +                // MINUTE (every so many minutes...)
  +                schedrun.add(Calendar.SECOND, getSecond());
  +                schedrun.add(Calendar.MINUTE, getMinute());
  +                runtime = schedrun.getTime().getTime();
  +                break;
   
  -    /**
  -     * Get the value of weekday.
  -     *
  -     * @return Value of weekday.
  -     */
  -    public int getWeekday()
  -    {
  -        return weekday;
  -    }
  +            case WEEK_DAY:
  +                // WEEKDAY (day of the week)
  +                schedrun.set(Calendar.SECOND, getSecond());
  +                schedrun.set(Calendar.MINUTE, getMinute());
  +                schedrun.set(Calendar.HOUR_OF_DAY, getHour());
  +                schedrun.set(Calendar.DAY_OF_WEEK, getWeekDay());
   
  -    /**
  -     * Set the value of weekday.
  -     *
  -     * @param v Value to assign to weekday.
  -     */
  -    public void setWeekday(int v)
  -    {
  -        this.weekday = v;
  -        setModified(true);
  -    }
  +                if(now.before(schedrun))
  +                {
  +                    // Scheduled time has NOT expired.
  +                    runtime = schedrun.getTime().getTime();
  +                }
  +                else
  +                {
  +                    // Scheduled time has expired; roll to the next week.
  +                    schedrun.add(Calendar.DAY_OF_WEEK, 7);
  +                    runtime = schedrun.getTime().getTime();
  +                }
  +                break;
   
  -    /**
  -     * Get the value of day_of_month.
  -     *
  -     * @return Value of day_of_month.
  -     */
  -    public int getDay_of_month()
  -    {
  -        return day_of_month;
  -    }
  +            case DAY_OF_MONTH:
  +                // DAY_OF_MONTH (date of the month)
  +                schedrun.set(Calendar.SECOND, getSecond());
  +                schedrun.set(Calendar.MINUTE, getMinute());
  +                schedrun.set(Calendar.HOUR_OF_DAY, getHour());
  +                schedrun.set(Calendar.DAY_OF_MONTH, getDayOfMonth());
   
  -    /**
  -     * Set the value of day_of_month.
  -     *
  -     * @param v Value to assign to day_of_month.
  -     */
  -    public void setDay_of_month(int v)
  -    {
  -        this.day_of_month = v;
  -        setModified(true);
  -    }
  +                if(now.before(schedrun))
  +                {
  +                    // Scheduled time has NOT expired.
  +                    runtime = schedrun.getTime().getTime();
  +                }
  +                else
  +                {
  +                    // Scheduled time has expired; roll to the next month.
  +                    schedrun.add(Calendar.MONTH, 1);
  +                    runtime = schedrun.getTime().getTime();
  +                }
  +                break;
   
  -    /**
  -     * Self-preservation.
  -     *
  -     * @exception Exception, a generic exception.
  -     */
  -    public void save()
  -        throws Exception
  -    {
  -        Criteria criteria = new Criteria(9)
  -            .add(JobEntryPeer.SECOND, getSecond())
  -            .add(JobEntryPeer.MINUTE, getMinute())
  -            .add(JobEntryPeer.HOUR, getHour())
  -            .add(JobEntryPeer.WEEKDAY, getWeekday())
  -            .add(JobEntryPeer.DAY_OF_MONTH, getDay_of_month())
  -            .add(JobEntryPeer.TASK, getTask())
  -            .add(JobEntryPeer.EMAIL, getEmail())
  -            .add(JobEntryPeer.PROPERTY, getProperty());
  -
  -        NumberKey nk = (NumberKey)getPrimaryKey();
  -        long key = 0;
  -        if (nk != null)
  -        {
  -            key = ((NumberKey)getPrimaryKey()).getBigDecimal().longValue();
  -        }
  -        if ( isModified() && key > 0)
  -        {
  -            // This is an update.
  -            criteria.add(JobEntryPeer.OID, getPrimaryKey());
  -            JobEntryPeer.doUpdate(criteria);
  -            setModified(false);
  -        }
  -        else
  -        {
  -            setPrimaryKey( JobEntryPeer.doInsert(criteria) );
  -        }
  -    }
  +            case DAILY:
  +                // DAILY (certain hour:minutes of the day)
  +                schedrun.set(Calendar.SECOND, getSecond());
  +                schedrun.set(Calendar.MINUTE, getMinute());
  +                schedrun.set(Calendar.HOUR_OF_DAY, getHour());
   
  -    /**
  -     * not implemented
  -     *
  -     * @param conn
  -     * @throws Exception
  -     */
  -    public void save(Connection conn) throws Exception
  -    {
  -        throw new Exception("not implemented");
  -    }
  +                // Scheduled time has NOT expired.
  +                if(now.before(schedrun))
  +                {
  +                    runtime = schedrun.getTime().getTime();
  +                }
  +                else
  +                {
  +                    // Scheduled time has expired; roll forward 24 hours.
  +                    schedrun.add(Calendar.HOUR_OF_DAY, 24);
  +                    runtime = schedrun.getTime().getTime();
  +                }
  +                break;
   
  -    /**
  -     * not implemented
  -     *
  -     * @param dbname
  -     * @throws Exception
  -     */
  -    public void save(String dbname) throws Exception
  -    {
  -        throw new Exception("not implemented");
  +            default:
  +                // Do nothing.
  +        }
       }
   
  -
       /**
        * What schedule am I on?
        *
  @@ -516,27 +325,27 @@
        *
        * @return A number specifying the type of schedule. See
        * calcRunTime().
  -     * @exception Exception, a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       private int evaluateJobType()
  -        throws Exception
  +            throws TurbineException
       {
   
           // First start by checking if it's a day of the month job.
  -        if ( day_of_month < 0 )
  +        if(getDayOfMonth() < 0)
           {
               // Not a day of the month job... check weekday.
  -            if ( weekday < 0 )
  +            if(getWeekDay() < 0)
               {
                   // Not a weekday job...check if by the hour.
  -                if ( hour < 0 )
  +                if(getHour() < 0)
                   {
                       // Not an hourly job...check if it is by the minute
  -                    if ( minute < 0 )
  +                    if(getMinute() < 0)
                       {
                           // Not a by the minute job so must be by the second
  -                        if ( second < 0)
  -                            throw new Exception("Error in JobEntry. Bad Job parameter.");
  +                        if(getSecond() < 0)
  +                            throw new TurbineException("Error in JobEntry. Bad Job parameter.");
   
                           return SECOND;
                       }
  @@ -544,8 +353,8 @@
                       {
                           // Must be a job run by the minute so we need minutes and
                           // seconds.
  -                        if ( minute < 0 || second < 0 )
  -                            throw new Exception("Error in JobEntry. Bad Job parameter.");
  +                        if(getMinute() < 0 || getSecond() < 0)
  +                            throw new TurbineException("Error in JobEntry. Bad Job parameter.");
   
                           return MINUTE;
                       }
  @@ -554,8 +363,8 @@
                   {
                       // Must be a daily job by hours minutes, and seconds.  In
                       // this case, we need the minute, second, and hour params.
  -                    if ( minute < 0 || hour < 0 || second < 0)
  -                        throw new Exception("Error in JobEntry. Bad Job parameter.");
  +                    if(getMinute() < 0 || getHour() < 0 || getSecond() < 0)
  +                        throw new TurbineException("Error in JobEntry. Bad Job parameter.");
   
                       return DAILY;
                   }
  @@ -564,8 +373,8 @@
               {
                   // Must be a weekday job.  In this case, we need
                   // minute, second, and hour params
  -                if ( minute < 0 || hour < 0 || second < 0 )
  -                    throw new Exception("Error in JobEntry. Bad Job parameter.");
  +                if(getMinute() < 0 || getHour() < 0 || getSecond() < 0)
  +                    throw new TurbineException("Error in JobEntry. Bad Job parameter.");
   
                   return WEEK_DAY;
               }
  @@ -574,97 +383,25 @@
           {
               // Must be a day of the month job.  In this case, we need
               // minute, second, and hour params
  -            if ( minute < 0 || hour < 0 )
  -                throw new Exception("Error in JobEntry. Bad Job parameter.");
  +            if(getMinute() < 0 || getHour() < 0)
  +                throw new TurbineException("Error in JobEntry. Bad Job parameter.");
   
               return DAY_OF_MONTH;
           }
       }
   
  -    /**
  -     * Used for ordering Jobentries
  -     * Note: this comparator imposes orderings that are inconsistent with
  -     * equals.
  -     *
  -     * @param je The first <code>JobEntry</code> object.
  -     * @return An <code>int</code> indicating the result of the comparison.
  -     */
  -    public int compareTo(Object je)
  -    {
  -        long obj1Time = this.getNextRuntime();
  -        long obj2Time = ((JobEntry)je).getNextRuntime();
  -        if (obj1Time > obj2Time)
  -        {
  -            return 1;
  -        }
  -        else if (obj1Time < obj2Time)
  -        {
  -            return -1;
  -        }
  -        else
  -        {
  -            return 0;
  -        }
  -    }
  +}
  +
  +
  +
  +
  +
  +
  +
  +
   
  -    /**
  -     * Compare this Job with another.
  -     *
  -     * @param je The JobEntry object to compare to.
  -     * @return True if they're the same.
  -     */
  -    public boolean equals(Object je)
  -    {
  -        if ( !( je instanceof JobEntry ) )
  -            return false;
   
  -        return ( ((JobEntry)je).getPrimaryKey().equals(this.getPrimaryKey()) );
  -    }
   
  -    /**
  -     * Sets whether the job is running.
  -     *
  -     * @param isActive Whether the job is running.
  -     */
  -    public void setActive(boolean isActive)
  -    {
  -        jobIsActive = isActive;
  -    }
   
  -    /**
  -     * Check to see if job is currently active/running
  -     *
  -     * @return true if job is currently geing run by the
  -     *  workerthread, otherwise false
  -     */
  -     public boolean isActive()
  -     {
  -        return jobIsActive;
  -     }
   
  -    /**
  -     * Set job properties
  -     *
  -     */
  -    public void setProperty(Hashtable prop)
  -    {
  -        jobProp = prop;
  -        setModified(true);
  -    }
   
  -    /**
  -     * Get extra job properties
  -     *
  -     */
  -    public Hashtable getProperty()
  -    {
  -        if ( jobProp == null )
  -        {
  -            return new Hashtable(89);
  -        }
  -        else
  -        {
  -            return jobProp;
  -        }
  -    }
  -}
  
  
  
  1.2       +35 -51    jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/JobQueue.java
  
  Index: JobQueue.java
  ===================================================================
  RCS file: /home/cvs/jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/JobQueue.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- JobQueue.java	16 Aug 2001 05:09:14 -0000	1.1
  +++ JobQueue.java	20 Jan 2003 21:52:13 -0000	1.2
  @@ -25,13 +25,13 @@
    *    Alternately, this acknowledgment may appear in the software itself,
    *    if and wherever such third-party acknowledgments normally appear.
    *
  - * 4. The names "Apache" and "Apache Software Foundation" and 
  - *    "Apache Turbine" must not be used to endorse or promote products 
  - *    derived from this software without prior written permission. For 
  + * 4. The names "Apache" and "Apache Software Foundation" and
  + *    "Apache Turbine" must not be used to endorse or promote products
  + *    derived from this software without prior written permission. For
    *    written permission, please contact apache@apache.org.
    *
    * 5. Products derived from this software may not be called "Apache",
  - *    "Apache Turbine", nor may "Apache" appear in their name, without 
  + *    "Apache Turbine", nor may "Apache" appear in their name, without
    *    prior written permission of the Apache Software Foundation.
    *
    * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  @@ -54,19 +54,21 @@
    * <http://www.apache.org/>.
    */
   
  +import java.util.Collections;
  +import java.util.Comparator;
   import java.util.List;
   import java.util.Vector;
  -import org.apache.turbine.util.Comparable;
  -import org.apache.turbine.util.QuickSort;
  +
  +import org.apache.turbine.util.TurbineException;
   
   /**
    * Queue for the scheduler.
    *
    * @author <a href="mailto:mbryson@mont.mindspring.com">Dave Bryson</a>
  + * @author <a href="mailto:quintonm@bellsouth.net">Quinton McCombs</a>
    * @version $Id$
    */
   public class JobQueue
  -    implements Comparable
   {
       /**
        * The queue of <code>JobEntry</code> objects.
  @@ -75,11 +77,8 @@
   
       /**
        * Creates a new instance.
  -     *
  -     * @exception Exception A generic exception.
        */
       public JobQueue()
  -        throws Exception
       {
           queue = new Vector(10);
       }
  @@ -92,9 +91,9 @@
        */
       public JobEntry getNext()
       {
  -        if ( queue.size() > 0 )
  +        if(queue.size() > 0)
           {
  -            return (JobEntry)queue.elementAt(0);
  +            return (JobEntry) queue.elementAt(0);
           }
           else
           {
  @@ -112,18 +111,18 @@
       {
           int index = -1;
   
  -        if ( je != null )
  +        if(je != null)
           {
               index = queue.indexOf(je);
           }
   
  -        if ( index < 0 )
  +        if(index < 0)
           {
               return null;
           }
           else
           {
  -            return (JobEntry)queue.elementAt(index);
  +            return (JobEntry) queue.elementAt(index);
           }
       }
   
  @@ -134,9 +133,9 @@
        */
       public Vector list()
       {
  -        if ( queue != null && queue.size() > 0 )
  +        if(queue != null && queue.size() > 0)
           {
  -            return (Vector)queue.clone();
  +            return (Vector) queue.clone();
           }
           else
           {
  @@ -163,7 +162,7 @@
        */
       public synchronized void batchLoad(List jobEntries)
       {
  -        if (jobEntries != null)
  +        if(jobEntries != null)
           {
               queue.addAll(jobEntries);
               sortQueue();
  @@ -188,7 +187,11 @@
        * @param je A JobEntry with the job to modify
        */
       public synchronized void modify(JobEntry je)
  +            throws TurbineException
       {
  +        remove(je);
  +        je.calcRunTime();
  +        this.add(je);
           sortQueue();
       }
   
  @@ -196,51 +199,32 @@
        * Update the job for its next run time.
        *
        * @param je A JobEntry to be updated.
  -     * @exception Exception, a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public synchronized void updateQueue(JobEntry je)
  -        throws Exception
  +            throws TurbineException
       {
           je.calcRunTime();
           sortQueue();
       }
   
       /**
  -     * Re-sort the existing queue.  Consumers of this method should be 
  +     * Re-sort the existing queue.  Consumers of this method should be
        * <code>synchronized</code>.
        */
       private void sortQueue()
       {
  -        // First sort.
  -        Object data[] = new Object[queue.size()];
  -        queue.copyInto(data);
  -        QuickSort.quickSort(data, 0, data.length - 1, this);
  -        queue.removeAllElements();
  -
  -        for (int i = 0; i < data.length; i++)
  +        Comparator aComparator = new Comparator()
           {
  -            queue.add(data[i]);
  -        }
  -    }
  +            public int compare(Object o1, Object o2)
  +            {
  +                Long time1 = new Long(((JobEntry) o1).getNextRuntime());
  +                Long time2 = new Long(((JobEntry) o2).getNextRuntime());
  +                return (time1.compareTo(time2));
  +            }
  +        };
   
  -    /**
  -     * Compare to another <code>JobEntry</code>.  Used by the
  -     * <code>QuickSort</code> class to determine sort order.
  -     *
  -     * @param je1 The first <code>JobEntry</code> object.
  -     * @param je2 The second <code>JobEntry</code> object.
  -     * @return An <code>int</code> indicating the result of the comparison.
  -     */
  -    public int compare(Object je1, Object je2)
  -    {
  -        long obj1Time = ((JobEntry)je1).getNextRuntime();
  -        long obj2Time = ((JobEntry)je2).getNextRuntime();
  -        
  -        if (obj1Time > obj2Time)
  -            return 1;
  -        else if (obj1Time < obj2Time)
  -            return -1;
  -        else
  -            return 0;
  +        Collections.sort(queue, aComparator);
       }
   }
  +
  
  
  
  1.3       +51 -22    jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/ScheduleService.java
  
  Index: ScheduleService.java
  ===================================================================
  RCS file: /home/cvs/jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/ScheduleService.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- ScheduleService.java	11 Jan 2003 18:42:34 -0000	1.2
  +++ ScheduleService.java	20 Jan 2003 21:52:13 -0000	1.3
  @@ -25,13 +25,13 @@
    *    Alternately, this acknowledgment may appear in the software itself,
    *    if and wherever such third-party acknowledgments normally appear.
    *
  - * 4. The names "Apache" and "Apache Software Foundation" and 
  - *    "Apache Turbine" must not be used to endorse or promote products 
  - *    derived from this software without prior written permission. For 
  + * 4. The names "Apache" and "Apache Software Foundation" and
  + *    "Apache Turbine" must not be used to endorse or promote products
  + *    derived from this software without prior written permission. For
    *    written permission, please contact apache@apache.org.
    *
    * 5. Products derived from this software may not be called "Apache",
  - *    "Apache Turbine", nor may "Apache" appear in their name, without 
  + *    "Apache Turbine", nor may "Apache" appear in their name, without
    *    prior written permission of the Apache Software Foundation.
    *
    * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  @@ -54,61 +54,90 @@
    * <http://www.apache.org/>.
    */
   
  -import java.util.Vector;
  +import java.util.List;
  +
   import org.apache.turbine.services.Service;
  +import org.apache.turbine.util.TurbineException;
   
   /**
    * ScheduleService interface.
    *
    * @author <a href="mailto:mbryson@mont.mindspring.com">Dave Bryson</a>
  + * @author <a href="mailto:quintonm@bellsouth.net">Quinton McCombs</a>
    * @version $Id$
    */
   public interface ScheduleService
  -    extends Service
  +        extends Service
   {
  -    static final String SERVICE_NAME = "SchedulerService";
  +    /** Name of service */
  +    public static final String SERVICE_NAME = "SchedulerService";
  +
  +    /** TR.props key for intially activating the scheduler thread */
  +    public static final String INTIALLY_ACTIVE = "enabled";
  +
  +    /** TR.props key for the logger */
  +    public static final String LOGGER_NAME = "scheduler";
   
       /**
        * Get a specific Job from Storage.
        *
        * @param oid The int id for the job.
        * @return A JobEntry.
  -     * @exception Exception, a generic exception.
  +     * @exception TurbineException a generic exception.
        */
  -    JobEntry getJob(int oid)
  -        throws Exception;
  +    public JobEntry getJob(int oid)
  +            throws TurbineException;
   
       /**
        * Add a new job to the queue.
        *
        * @param je A JobEntry with the job to add.
  -     * @exception Exception, a generic exception.
  +     * @exception TurbineException a generic exception.
        */
  -    void addJob(JobEntry je)
  -        throws Exception;
  +    public void addJob(JobEntry je)
  +            throws TurbineException;
   
       /**
        * Modify a Job.
        *
        * @param je A JobEntry with the job to modify
  -     * @exception Exception, a generic exception.
  +     * @exception TurbineException a generic exception.
        */
  -    void updateJob(JobEntry je)
  -        throws Exception;
  +    public void updateJob(JobEntry je)
  +            throws TurbineException;
   
       /**
        * Remove a job from the queue.
        *
        * @param je A JobEntry with the job to remove.
  -     * @exception Exception, a generic exception.
  +     * @exception TurbineException a generic exception.
        */
  -    void removeJob(JobEntry je)
  -        throws Exception;
  +    public void removeJob(JobEntry je)
  +            throws TurbineException;
   
       /**
        * List jobs in the queue.  This is used by the scheduler UI.
        *
  -     * @return A Vector of jobs.
  +     * @return A List of jobs.
  +     */
  +    public List listJobs();
  +
  +    /**
  +     * Determines if the scheduler service is currently active.
  +     *
  +     * @return Status of the scheduler service.
        */
  -    Vector listJobs();
  +    public boolean isEnabled();
  +
  +    /**
  +     * Starts the scheduler if not already running.
  +     */
  +    public void startScheduler();
  +
  +    /**
  +     * Stops the scheduler if ti is currently running.
  +     */
  +    public void stopScheduler();
  +
   }
  +
  
  
  
  1.8       +66 -58    jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/TurbineNonPersistentSchedulerService.java
  
  Index: TurbineNonPersistentSchedulerService.java
  ===================================================================
  RCS file: /home/cvs/jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/TurbineNonPersistentSchedulerService.java,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -r1.7 -r1.8
  --- TurbineNonPersistentSchedulerService.java	13 Jan 2003 21:14:29 -0000	1.7
  +++ TurbineNonPersistentSchedulerService.java	20 Jan 2003 21:52:13 -0000	1.8
  @@ -56,11 +56,13 @@
   
   import java.util.Vector;
   import javax.servlet.ServletConfig;
  +
   import org.apache.commons.logging.Log;
   import org.apache.commons.logging.LogFactory;
   import org.apache.torque.om.NumberKey;
   import org.apache.torque.om.ObjectKey;
   import org.apache.turbine.services.resources.TurbineResources;
  +import org.apache.turbine.util.TurbineException;
   
   /**
    * Service for a cron like scheduler that uses the
  @@ -72,54 +74,59 @@
    * extend ScheduledJob.
    *
    *<PRE>
  -   scheduler.jobs=scheduledJobName,scheduledJobName2
  -
  -   scheduler.job.scheduledJobName.ID=1
  -   scheduler.job.scheduledJobName.SECOND=-1
  -   scheduler.job.scheduledJobName.MINUTE=-1
  -   scheduler.job.scheduledJobName.HOUR=7
  -   scheduler.job.scheduledJobName.WEEKDAY=-1
  -   scheduler.job.scheduledJobName.DAY_OF_MONTH=-1
  -
  -   scheduler.job.scheduledJobName2.ID=1
  -   scheduler.job.scheduledJobName2.SECOND=-1
  -   scheduler.job.scheduledJobName2.MINUTE=-1
  -   scheduler.job.scheduledJobName2.HOUR=7
  -   scheduler.job.scheduledJobName2.WEEKDAY=-1
  -   scheduler.job.scheduledJobName2.DAY_OF_MONTH=-1
  -   </PRE>
  + *
  + * services.SchedulerService.scheduler.jobs=scheduledJobName,scheduledJobName2
  + *
  + * services.SchedulerService.scheduler.job.scheduledJobName.ID=1
  + * services.SchedulerService.scheduler.job.scheduledJobName.SECOND=-1
  + * services.SchedulerService.scheduler.job.scheduledJobName.MINUTE=-1
  + * services.SchedulerService.scheduler.job.scheduledJobName.HOUR=7
  + * services.SchedulerService.scheduler.job.scheduledJobName.WEEKDAY=-1
  + * services.SchedulerService.scheduler.job.scheduledJobName.DAY_OF_MONTH=-1
  + *
  + * services.SchedulerService.scheduler.job.scheduledJobName2.ID=1
  + * services.SchedulerService.scheduler.job.scheduledJobName2.SECOND=-1
  + * services.SchedulerService.scheduler.job.scheduledJobName2.MINUTE=-1
  + * services.SchedulerService.scheduler.job.scheduledJobName2.HOUR=7
  + * services.SchedulerService.scheduler.job.scheduledJobName2.WEEKDAY=-1
  + * services.SchedulerService.scheduler.job.scheduledJobName2.DAY_OF_MONTH=-1
  + *
  + * </PRE>
    *
    * Based on TamboraSchedulerService written by John Thorhauer.
    *
    * @author <a href="mailto:ekkerbj@netscpae.net">Jeff Brekke</a>
    * @author <a href="mailto:john@zenplex.com">John Thorhauer</a>
  + * @author <a href="mailto:quintonm@bellsouth.net">Quinton McCombs</a>
  + * @version $Id$
    */
   public class TurbineNonPersistentSchedulerService
  -    extends TurbineSchedulerService
  +        extends TurbineSchedulerService
   {
       /** Logging */
  -    private static Log log = LogFactory.getLog(
  -        TurbineNonPersistentSchedulerService.class);
  +    private static Log log = LogFactory.getLog(ScheduleService.LOGGER_NAME);
   
       /**
        * Constructor.
        *
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public TurbineNonPersistentSchedulerService()
  -        throws Exception
  +            throws TurbineException
       {
           super();
       }
   
       /**
  -     * Initializes the SchedulerService.
  -     * This is a zero parameter variant which queries the Turbine Servlet
  -     * for its config.
  +     * Called the first time the Service is used.<br>
  +     *
  +     * Load all the jobs from cold storage.  Add jobs to the queue
  +     * (sorted in ascending order by runtime) and start the scheduler
  +     * thread.
        */
       public void init()
       {
  -        if (getInit())
  +        if(getInit())
           {
               return;
           }
  @@ -135,39 +142,40 @@
               Vector jobs = new Vector();
               // If there are scheduler.jobs defined then set up a job vector
               // for the scheduleQueue
  -            if (!jobProps.isEmpty())
  +            if(!jobProps.isEmpty())
               {
  -                for (int i = 0; i < jobProps.size(); i++)
  +                for(int i = 0; i < jobProps.size(); i++)
                   {
  -                    String jobName = (String)jobProps.elementAt(i);
  -                    String jobPrefix = "scheduler.job." + jobName ;
  +                    String jobName = (String) jobProps.elementAt(i);
  +                    String jobPrefix = "scheduler.job." + jobName;
   
  -                    if ((TurbineResources.getString(jobPrefix + ".ID", null))
  -                        == null)
  +                    if((TurbineResources.getString(jobPrefix + ".ID", null))
  +                            == null)
                       {
                           throw new Exception(
  -                        "There is an error in the TurbineResources.properties file. \n"
  -                        + jobPrefix + ".ID is not found.\n");
  +                                "There is an error in the TurbineResources.properties file. \n"
  +                                + jobPrefix + ".ID is not found.\n");
                       }
   
                       int sec = TurbineResources.getInt(jobPrefix + ".SECOND", -1);
                       int min = TurbineResources.getInt(jobPrefix + ".MINUTE", -1);
  -                    int hr  = TurbineResources.getInt(jobPrefix + ".HOUR", -1);
  +                    int hr = TurbineResources.getInt(jobPrefix + ".HOUR", -1);
                       int wkday = TurbineResources.getInt(jobPrefix + ".WEEKDAY", -1);
                       int dayOfMonth = TurbineResources.getInt(jobPrefix + ".DAY_OF_MONTH", -1);
   
  -                    JobEntry je = new JobEntry(sec,
  -                                               min,
  -                                               hr,
  -                                               wkday,
  -                                               dayOfMonth,
  -                                               jobName);
  +                    JobEntry je = new JobEntry(
  +                            sec,
  +                            min,
  +                            hr,
  +                            wkday,
  +                            dayOfMonth,
  +                            jobName);
                       jobs.addElement(je);
   
                   }
               }
   
  -            if (jobs != null && jobs.size() > 0)
  +            if(jobs != null && jobs.size() > 0)
               {
                   scheduleQueue.batchLoad(jobs);
                   restart();
  @@ -176,10 +184,10 @@
               setInit(true);
               log.info("TurbineNonPersistentSchedulerService init()....finished!");
           }
  -        catch (Exception e)
  +        catch(Exception e)
           {
               log.error("Cannot initialize TurbineNonPersistentSchedulerService!: "
  -                + e );
  +                    + e);
           }
       }
   
  @@ -203,17 +211,17 @@
        *
        * @param oid The int id for the job.
        * @return A JobEntry.
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public JobEntry getJob(int oid)
  -        throws Exception
  +            throws TurbineException
       {
           JobEntry je = new JobEntry(-1,
  -                                   -1,
  -                                   -1,
  -                                   -1,
  -                                   -1,
  -                                   null);
  +                -1,
  +                -1,
  +                -1,
  +                -1,
  +                null);
           je.setPrimaryKey((ObjectKey) new NumberKey(oid));
           return scheduleQueue.getJob(je);
       }
  @@ -222,10 +230,10 @@
        * Add a new job to the queue.
        *
        * @param je A JobEntry with the job to add.
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public void addJob(JobEntry je)
  -        throws Exception
  +            throws TurbineException
       {
           // Add to the queue.
           scheduleQueue.add(je);
  @@ -236,10 +244,10 @@
        * Remove a job from the queue.
        *
        * @param je A JobEntry with the job to remove.
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public void removeJob(JobEntry je)
  -        throws Exception
  +            throws TurbineException
       {
           // Remove from the queue.
           scheduleQueue.remove(je);
  @@ -250,10 +258,10 @@
        * Modify a Job.
        *
        * @param je A JobEntry with the job to modify
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public void updateJob(JobEntry je)
  -        throws Exception
  +            throws TurbineException
       {
           try
           {
  @@ -265,7 +273,7 @@
               log.error("Problem updating Scheduled Job: " + e);
           }
           // Update the queue.
  -       scheduleQueue.modify(je);
  -       restart();
  +        scheduleQueue.modify(je);
  +        restart();
       }
   }
  
  
  
  1.2       +36 -9     jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/TurbineScheduler.java
  
  Index: TurbineScheduler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/TurbineScheduler.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- TurbineScheduler.java	17 Jan 2003 21:39:48 -0000	1.1
  +++ TurbineScheduler.java	20 Jan 2003 21:52:13 -0000	1.2
  @@ -3,6 +3,7 @@
   import java.util.List;
   
   import org.apache.turbine.services.TurbineServices;
  +import org.apache.turbine.util.TurbineException;
   
   /* ====================================================================
    * The Apache Software License, Version 1.1
  @@ -74,10 +75,10 @@
        *
        * @param oid The int id for the job.
        * @return A JobEntry.
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public static JobEntry getJob(int oid)
  -            throws Exception
  +            throws TurbineException
       {
           return getService().getJob(oid);
       }
  @@ -86,10 +87,10 @@
        * Add a new job to the queue.
        *
        * @param je A JobEntry with the job to add.
  -     * @exception Exception, a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       void addJob(JobEntry je)
  -            throws Exception
  +            throws TurbineException
       {
           getService().addJob(je);
       }
  @@ -98,10 +99,10 @@
        * Modify a Job.
        *
        * @param je A JobEntry with the job to modify
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public static void updateJob(JobEntry je)
  -            throws Exception
  +            throws TurbineException
       {
           getService().updateJob(je);
       }
  @@ -110,10 +111,10 @@
        * Remove a job from the queue.
        *
        * @param je A JobEntry with the job to remove.
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public static void removeJob(JobEntry je)
  -            throws Exception
  +            throws TurbineException
       {
           getService().removeJob(je);
       }
  @@ -126,6 +127,32 @@
       public static List listJobs()
       {
           return getService().listJobs();
  +    }
  +
  +    /**
  +     * Determines if the scheduler service is currently active.
  +     *
  +     * @return Status of the scheduler service.
  +     */
  +    public static boolean isEnabled()
  +    {
  +        return getService().isEnabled();
  +    }
  +
  +    /**
  +     * Starts the scheduler if not already running.
  +     */
  +    public static void startScheduler()
  +    {
  +        getService().startScheduler();
  +    }
  +
  +    /**
  +     * Stops the scheduler if ti is currently running.
  +     */
  +    public static void stopScheduler()
  +    {
  +        getService().stopScheduler();
       }
   
       /**
  
  
  
  1.8       +119 -74   jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/TurbineSchedulerService.java
  
  Index: TurbineSchedulerService.java
  ===================================================================
  RCS file: /home/cvs/jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/TurbineSchedulerService.java,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -r1.7 -r1.8
  --- TurbineSchedulerService.java	13 Jan 2003 21:14:29 -0000	1.7
  +++ TurbineSchedulerService.java	20 Jan 2003 21:52:13 -0000	1.8
  @@ -54,42 +54,42 @@
    * <http://www.apache.org/>.
    */
   
  +import java.util.Iterator;
   import java.util.List;
  -import java.util.Vector;
   import javax.servlet.ServletConfig;
  +
   import org.apache.commons.logging.Log;
   import org.apache.commons.logging.LogFactory;
  +import org.apache.torque.TorqueException;
   import org.apache.torque.util.Criteria;
   import org.apache.turbine.services.InitializationException;
   import org.apache.turbine.services.TurbineBaseService;
  -import org.apache.turbine.services.resources.TurbineResources;
  +import org.apache.turbine.util.TurbineException;
   
   /**
    * Service for a cron like scheduler.
    *
    * @author <a href="mailto:mbryson@mont.mindspring.com">Dave Bryson</a>
  + * @author <a href="mailto:quintonm@bellsouth.net">Quinton McCombs</a>
    * @version $Id$
    */
   public class TurbineSchedulerService
  -    extends TurbineBaseService
  -    implements ScheduleService
  +        extends TurbineBaseService
  +        implements ScheduleService
   {
       /** Logging */
  -    private static Log log = LogFactory.getLog(TurbineSchedulerService.class);
  +    private static Log log = LogFactory.getLog(ScheduleService.LOGGER_NAME);
   
  -    /**
  -     * The queue.
  -     */
  +    /** The queue */
       protected JobQueue scheduleQueue = null;
   
  -    /**
  -     * The main loop for starting jobs.
  -     */
  +    /** Current status of the scheduler */
  +    private boolean enabled = false;
  +
  +    /** The main loop for starting jobs. */
       protected MainLoop mainLoop;
   
  -    /**
  -     * The thread used to process commands.
  -     */
  +    /** The thread used to process commands.  */
       protected Thread thread;
   
       /**
  @@ -103,43 +103,40 @@
   
       /**
        * Initializes the SchedulerService.
  -     * This is a zero parameter variant which queries the Turbine Servlet
  -     * for its config.
        *
        * @throws InitializationException Something went wrong in the init
        *         stage
        */
       public void init()
  -        throws InitializationException
  +            throws InitializationException
       {
           try
           {
  -            // START SCHEDULER HERE
  -            if (TurbineResources.getBoolean("scheduler.enabled", false))
  -            {
  -                scheduleQueue = new JobQueue();
  -                mainLoop = new MainLoop();
  +            scheduleQueue = new JobQueue();
  +            mainLoop = new MainLoop();
   
  -                // Load all from cold storage.
  -                List jobs  = JobEntryPeer.doSelect(new Criteria());
  +            // Load all from cold storage.
  +            List jobs = JobEntryPeer.doSelect(new Criteria());
   
  -                if (jobs != null && jobs.size() > 0)
  +            if(jobs != null && jobs.size() > 0)
  +            {
  +                Iterator it = jobs.iterator();
  +                while(it.hasNext())
  +                {
  +                    ((JobEntry) it.next()).calcRunTime();
  +                }
  +                scheduleQueue.batchLoad(jobs);
  +                if(getConfiguration().getBoolean("enabled", true))
                   {
  -                    scheduleQueue.batchLoad(jobs);
                       restart();
                   }
  -
  -                setInit(true);
  -            }
  -            else
  -            {
  -                log.info("TurbineSchedulerService was not started "
  -                        + "because scheduler.enabled is not 'true' in the "
  -                        + "TurbineResources.properties file.");
               }
  +
  +            setInit(true);
           }
  -        catch (Exception e)
  +        catch(Exception e)
           {
  +            log.error("Could not initialize the scheduler service", e);
               throw new InitializationException(
                       "TurbineSchedulerService failed to initialize", e);
           }
  @@ -156,7 +153,7 @@
        * @deprecated use init() instead.
        */
       public void init(ServletConfig config)
  -        throws InitializationException
  +            throws InitializationException
       {
           init();
       }
  @@ -168,7 +165,7 @@
        */
       public void shutdown()
       {
  -        if (getThread() != null)
  +        if(getThread() != null)
           {
               getThread().interrupt();
           }
  @@ -179,57 +176,69 @@
        *
        * @param oid The int id for the job.
        * @return A JobEntry.
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public JobEntry getJob(int oid)
  -        throws Exception
  +            throws TurbineException
       {
  -        JobEntry je = JobEntryPeer.getJob(oid);
  -        return scheduleQueue.getJob(je);
  +        try
  +        {
  +            JobEntry je = JobEntryPeer.retrieveByPK(oid);
  +            return scheduleQueue.getJob(je);
  +        }
  +        catch(TorqueException e)
  +        {
  +            String errorMessage = "Error retrieving job from persistent storage.";
  +            log.error(errorMessage, e);
  +            throw new TurbineException(errorMessage, e);
  +        }
       }
   
       /**
        * Add a new job to the queue.
        *
        * @param je A JobEntry with the job to add.
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public void addJob(JobEntry je)
  -        throws Exception
  +            throws TurbineException
       {
           try
           {
  +            // Calculate the runtime to make sure the entry will be placed
  +            // at the right order
  +            je.calcRunTime();
  +
               // Save to DB.
               je.save();
  +
  +            // Add to the queue.
  +            scheduleQueue.add(je);
  +            restart();
           }
  -        catch (Exception e)
  +        catch(Exception e)
           {
               // Log problems.
               log.error("Problem saving new Scheduled Job: " + e);
           }
  -        // Add to the queue.
  -        scheduleQueue.add(je);
  -        restart();
       }
   
       /**
        * Remove a job from the queue.
        *
        * @param je A JobEntry with the job to remove.
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public void removeJob(JobEntry je)
  -        throws Exception
  +            throws TurbineException
       {
           // First remove from DB.
           try
           {
  -            Criteria c = new Criteria()
  -                .add(JobEntryPeer.OID, je.getPrimaryKey());
  -
  +            Criteria c = new Criteria().add(JobEntryPeer.JOB_ID, je.getPrimaryKey());
               JobEntryPeer.doDelete(c);
           }
  -        catch (Exception ouch)
  +        catch(Exception ouch)
           {
               // Log problem.
               log.error("Problem removing Scheduled Job: " + ouch);
  @@ -244,37 +253,70 @@
        * Modify a Job.
        *
        * @param je A JobEntry with the job to modify
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       public void updateJob(JobEntry je)
  -        throws Exception
  +            throws TurbineException
       {
           try
           {
               je.calcRunTime();
               je.save();
  +
  +            // Update the queue.
  +            scheduleQueue.modify(je);
  +            restart();
           }
  -        catch (Exception e)
  +        catch(Exception e)
           {
               // Log problems.
               log.error("Problem updating Scheduled Job: " + e);
           }
  -        // Update the queue.
  -       scheduleQueue.modify(je);
  -       restart();
       }
   
       /**
        * List jobs in the queue.  This is used by the scheduler UI.
        *
  -     * @return A Vector of jobs.
  +     * @return A List of jobs.
        */
  -    public Vector listJobs()
  +    public List listJobs()
       {
           return scheduleQueue.list();
       }
   
       /**
  +     * Determines if the scheduler service is currently enabled.
  +     *
  +     * @return Status of the scheduler service.
  +     */
  +    public boolean isEnabled()
  +    {
  +        return (getThread() == null ? false : true);
  +    }
  +
  +    /**
  +     * Starts or restarts the scheduler if not already running.
  +     */
  +    public void startScheduler()
  +    {
  +        restart();
  +    }
  +
  +    /**
  +     * Stops the scheduler if it is currently running.
  +     */
  +    public void stopScheduler()
  +    {
  +        log.info("Stopping job scheduler");
  +        Thread thread = getThread();
  +        if(thread != null)
  +        {
  +            thread.interrupt();
  +        }
  +        enabled = false;
  +    }
  +
  +    /**
        * Return the thread being used to process commands, or null if
        * there is no such thread.  You can use this to invoke any
        * special methods on the thread, for example, to interrupt it.
  @@ -302,14 +344,16 @@
        */
       public synchronized void restart()
       {
  -        if (thread == null)
  +        log.info("Starting job scheduler");
  +        enabled = true;
  +        if(thread == null)
           {
               // Create the the housekeeping thread of the scheduler. It will wait
               // for the time when the next task needs to be started, and then
               // launch a worker thread to execute the task.
               thread = new Thread(mainLoop, ScheduleService.SERVICE_NAME);
               // Indicate that this is a system thread. JVM will quit only when there
  -            // are no more active user threads. Settings threads spawned internally
  +            // are no more enabled user threads. Settings threads spawned internally
               // by Turbine as daemons allows commandline applications using Turbine
               // to terminate in an orderly manner.
               thread.setDaemon(true);
  @@ -326,19 +370,19 @@
        *  interrupted.
        *
        * @return A JobEntry.
  -     * @exception Exception a generic exception.
  +     * @exception TurbineException a generic exception.
        */
       private synchronized JobEntry nextJob()
  -        throws Exception
  +            throws TurbineException
       {
           try
           {
  -            while (!Thread.interrupted())
  +            while(!Thread.interrupted())
               {
                   // Grab the next job off the queue.
                   JobEntry je = scheduleQueue.getNext();
   
  -                if (je == null)
  +                if(je == null)
                   {
                       // Queue must be empty. Wait on it.
                       wait();
  @@ -348,7 +392,7 @@
                       long now = System.currentTimeMillis();
                       long when = je.getNextRuntime();
   
  -                    if (when > now)
  +                    if(when > now)
                       {
                           // Wait till next runtime.
                           wait(when - now);
  @@ -363,7 +407,7 @@
                   }
               }
           }
  -        catch (InterruptedException ex)
  +        catch(InterruptedException ex)
           {
           }
   
  @@ -377,7 +421,7 @@
        * allow others to directly invoke run, which is not supported.
        */
       protected class MainLoop
  -        implements Runnable
  +            implements Runnable
       {
           /**
            * Method to run the class.
  @@ -386,10 +430,10 @@
           {
               try
               {
  -                for(; ; )
  +                while(enabled)
                   {
                       JobEntry je = nextJob();
  -                    if (je != null)
  +                    if(je != null)
                       {
                           // Start the thread to run the job.
                           Runnable wt = new WorkerThread(je);
  @@ -402,10 +446,11 @@
                       }
                   }
               }
  -            catch (Exception e)
  +            catch(Exception e)
               {
                   // Log error.
                   log.error("Error running a Scheduled Job: " + e);
  +                enabled = false;
               }
               finally
               {
  
  
  
  1.3       +19 -19    jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/WorkerThread.java
  
  Index: WorkerThread.java
  ===================================================================
  RCS file: /home/cvs/jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/WorkerThread.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- WorkerThread.java	20 Dec 2002 00:16:41 -0000	1.2
  +++ WorkerThread.java	20 Jan 2003 21:52:13 -0000	1.3
  @@ -25,13 +25,13 @@
    *    Alternately, this acknowledgment may appear in the software itself,
    *    if and wherever such third-party acknowledgments normally appear.
    *
  - * 4. The names "Apache" and "Apache Software Foundation" and 
  - *    "Apache Turbine" must not be used to endorse or promote products 
  - *    derived from this software without prior written permission. For 
  + * 4. The names "Apache" and "Apache Software Foundation" and
  + *    "Apache Turbine" must not be used to endorse or promote products
  + *    derived from this software without prior written permission. For
    *    written permission, please contact apache@apache.org.
    *
    * 5. Products derived from this software may not be called "Apache",
  - *    "Apache Turbine", nor may "Apache" appear in their name, without 
  + *    "Apache Turbine", nor may "Apache" appear in their name, without
    *    prior written permission of the Apache Software Foundation.
    *
    * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  @@ -56,9 +56,6 @@
   
   import org.apache.commons.logging.Log;
   import org.apache.commons.logging.LogFactory;
  -
  -import org.apache.turbine.TurbineConstants;
  -
   import org.apache.turbine.modules.ScheduledJobLoader;
   
   /**
  @@ -67,18 +64,19 @@
    * @author <a href="mailto:mbryson@mont.mindspring.com">Dave Bryson</a>
    * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
    * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
  + * @author <a href="mailto:quintonm@bellsouth.net">Quinton McCombs</a>
    * @version $Id$
    */
   public class WorkerThread
  -    implements Runnable
  +        implements Runnable
   {
       /**
        * The <code>JobEntry</code> to run.
        */
       private JobEntry je = null;
   
  -    /** Logging class from commons.logging */
  -    private static Log log = LogFactory.getLog(TurbineConstants.SCHEDULER_LOG_FACILITY);
  +    /** Logging */
  +    private static Log log = LogFactory.getLog(ScheduleService.LOGGER_NAME);
   
       /**
        * Creates a new worker to run the specified <code>JobEntry</code>.
  @@ -95,26 +93,28 @@
        */
       public void run()
       {
  -        if (je == null || je.isActive())
  +        if(je == null || je.isActive())
  +        {
               return;
  +        }
   
           try
           {
  -            if (! je.isActive())
  +            if(!je.isActive())
               {
                   je.setActive(true);
                   logStateChange("started");
                   ScheduledJobLoader.getInstance().exec(je, je.getTask());
               }
           }
  -        catch (Exception e)
  +        catch(Exception e)
           {
  -            log.error("Error in WorkerThread for sheduled job #" + 
  -                      je.getPrimaryKey() + ", task: " + je.getTask(), e);
  +            log.error("Error in WorkerThread for sheduled job #" +
  +                    je.getPrimaryKey() + ", task: " + je.getTask(), e);
           }
           finally
           {
  -            if (je.isActive())
  +            if(je.isActive())
               {
                   je.setActive(false);
                   logStateChange("completed");
  @@ -129,7 +129,7 @@
        */
       private final void logStateChange(String state)
       {
  -        log.debug("Scheduled job #" + je.getPrimaryKey() + ' ' + state + 
  -                  ", task: " + je.getTask());
  +        log.debug("Scheduled job #" + je.getPrimaryKey() + ' ' + state +
  +                ", task: " + je.getTask());
       }
   }
  
  
  
  1.1                  jakarta-turbine-2/src/java/org/apache/turbine/services/schedule/SchedulerTool.java
  
  Index: SchedulerTool.java
  ===================================================================
  package org.apache.turbine.services.schedule;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Turbine" must not be used to endorse or promote products
   *    derived from this software without prior written permission. For
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache Turbine", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import java.util.List;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.apache.turbine.services.TurbineServices;
  import org.apache.turbine.services.pull.ApplicationTool;
  import org.apache.turbine.util.TurbineException;
  
  /**
   * This tool is used to retrieve information about the job scheduler.
   *
   * @author <a href="mailto:qmccombs@nequalsone.com">Quinton McCombs</a>
   * @version $Id: SchedulerTool.java,v 1.1 2003/01/20 21:52:13 quintonm Exp $
   */
  public class SchedulerTool implements ApplicationTool
  {
      /** Used for logging */
      private static Log log = LogFactory.getLog(ScheduleService.LOGGER_NAME);
  
      /**
       * Initialize the pull tool
       */
      public void init(Object data)
      {
          if(!TurbineServices.getInstance().isRegistered(ScheduleService.SERVICE_NAME))
          {
              log.error("You can not use the SchedulerTool unless you enable the Scheduler Service!!!!");
          }
      }
  
      /**
       * Does nothing
       */
      public void refresh()
      {
      }
  
      /**
       * Gets the list of scheduled jobs.
       *
       * @return List of JobEntry objects.
       */
      public List getScheduledJobs()
      {
          return TurbineScheduler.listJobs();
      }
  
      /**
       * Determines if the scheduler service is currently enabled.
       */
      public boolean isEnabled()
      {
          return TurbineScheduler.isEnabled();
      }
  
      /**
       * Gets the job identified by the jobId.
       *
       * @param jobId Id of the job to retreive.
       * @return The job.  Null if the jobId is not found.
       */
      public JobEntry getJob(String jobId)
      {
          JobEntry je = null;
  
          try
          {
              je = TurbineScheduler.getJob(Integer.parseInt(jobId));
          }
          catch(TurbineException e)
          {
              log.error("Could not retreive job id #" + jobId, e);
          }
  
          return je;
      }
  
  }
  
  
  

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>