实现CronExpression的getFinalFireTime(),写的急,大家再改改!

class MyCronExpr extends CronExpression
{
    /**
     * 返回最后一次执行的时间;
     * @return
     */
    public Date getFinalFireTime()
    {
        Calendar ret = Calendar.getInstance();
        Integer day = getMaxField(this.daysOfMonth, "Day");
        
        ret.set(Calendar.YEAR, getMaxField(this.years, "Year"));                    //设置年
        ret.set(Calendar.MONTH, getMaxField(this.months, "Month") - 1);             //设置月
        if (day != 0)
            ret.set(Calendar.DAY_OF_MONTH, getMaxField(this.daysOfMonth, "Day"));   //设置日
        else
            ret.set(Calendar.DAY_OF_WEEK, getMaxField(this.daysOfWeek, "Week"));    //设置周
        if (this.nthdayOfWeek != 0)
        {
            ret.set(Calendar.WEEK_OF_MONTH, this.nthdayOfWeek);
        }
        
        ret.set(Calendar.HOUR_OF_DAY, getMaxField(this.hours, "Hour"));              //设置小时
        ret.set(Calendar.MINUTE, getMaxField(this.minutes, "Minute"));               //设置分钟
        ret.set(Calendar.SECOND, getMaxField(this.seconds, "Second"));               //设置秒
        
        return ret.getTime();
    }

    public MyCronExpr(String expr) throws ParseException
    {
        super(expr);
    }
    
    private Integer getMaxField(TreeSet set, String field)
    {
        if (set == null)
        {
            return null;
        }
        
        Integer ret = 0;
        Integer temp = 0;
        Integer maxVal = 0;
        
        if ("Year".equalsIgnoreCase(field))
        {
            maxVal = 2099;
        }
        else if("Month".equalsIgnoreCase(field))
        {
            maxVal = 12;
        }
        else if("Week".equalsIgnoreCase(field))
        {
            maxVal = 7;
        }
        else if("Day".equalsIgnoreCase(field))
        {
            maxVal = 31;
        }
        else if("Hour".equalsIgnoreCase(field))
        {
            maxVal = 23;
        }
        else if("Minute".equalsIgnoreCase(field))
        {
            maxVal = 59;
        }
        else if("Second".equalsIgnoreCase(field))
        {
            maxVal = 59;
        }
        
        Iterator item = set.iterator();
        while (item.hasNext())
        {
            temp = (Integer)item.next();
            if (temp > ret && temp <= maxVal)
            {   //取最大者;
                ret = temp;
            }
        }
        
        return ret;
    }
}

你可能感兴趣的:(cronExpression)