定时执行任务-Java WEB程序【绝对好用】

指定每一天某时某分执行某项任务的功能。
/***第一个类定时器任务类***/ 
package com.wisdom.smsframe.logic.smsend;
import java.util.Date;
import java.util.Timer;
import java.util.Calendar;
import java.io.IOException;
import com.wisdom.base.ConfigurationFile;
/**
 * Created on      2013-8-13
 * <p>Title:       J2EE程序_[定时任务管理器]_[公共类]</p>
 * <p>Description: [定时器]</p>
 * <p>Copyright:   xuqb (c) 2013</p>  
 * <p>Company:   xuqb工作室</p>
 * @developer      xuqb[155282323@qq.com]
 * @version        1.0
*/
public class TimerManager
{
    /**
     * <p>Description:[时间间隔,每天执行次数(每24小时执行一次)]</p>  
     * <p>Value:PERIOD_DAY</p>
     */ 
    private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
    /**
     * <p>Description:[时间间隔,每天执行次数(每五秒执行一次)]</p>  
     * <p>Value:PERIOD_DAY</p>
     */
    //private static final long PERIOD_DAY = 5*1000;
    /**
     * <p>Description:[构造方法]</p>
     * @constructor 方法.
     */
    public TimerManager()
    {
             //--获取配置文件中的时间
             String file_path = ConfigurationFile.getConfigFilePath(); //获取位于SMS/WEB-INF/SMCS.INI配置文件路径
        String commitCount = null; //配置文件中的预设小时和分钟(24小时制)
        try
        {
            commitCount = ConfigurationFile.getProfile(file_path,
                    "dsrwtime", "mytimer", ""); //提取代码,例如[dsrwtime] SmsCounts=10:38
        }
        catch (IOException ea)
        {
            ea.printStackTrace();
        }
        String[] objtime = null;
        //拆分从配置文件预设的小时和分钟;若没有,则默认零时零分执行(24小时制)
        if(commitCount !=null && !"".equals(commitCount))
     {
            objtime = commitCount.split(":");
        }
        else
        {
            objtime = new String[2];
            objtime[0]="0"; //零时(24小时制)
            objtime[1]="0"; //零分(24小时制)
        }
        int beginHour = Integer.parseInt(objtime[0]); //开始执行小时(24小时制)
        int beginMimu = Integer.parseInt(objtime[1]); //开始执行分钟(24小时制)
        Calendar calendar = Calendar.getInstance();
        /*** 定制每日某时:某分执行方法(24小时制) ***/
        calendar.set(Calendar.HOUR_OF_DAY, beginHour); //开始执行小时(24小时制)
        calendar.set(Calendar.MINUTE, beginMimu); //开始执行分钟(24小时制)
        calendar.set(Calendar.SECOND, 0); //开始执行秒(24小时制)
  Date date = calendar.getTime(); //第一次执行定时任务的时间  
        //如果第一次执行定时任务的时间 小于 当前的时间  
        //此时要在 第一次执行定时任务的时间 加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。  
        if (date.before(new Date()))
        {
            date = this.addDay(date, 0); //0代表增加0天
        }
        Timer timer = new Timer();
        NFDFlightDataTimerTask task = new NFDFlightDataTimerTask();
        //安排指定的任务在指定的时间开始进行重复的固定延迟执行。  
        timer.schedule(task, date, PERIOD_DAY);
    }
    /**
     *  Created on       2013-8-13 
     * <p>Description:   [增加或减少天数]</p>
     * @param date
     * @param num
     * @return
     * @developer:        xuqb[155282323@qq.com]
     * @update:           [日期YYYY-MM-DD][更改人姓名][E-mail]
     */
    public Date addDay(Date date, int num)
    {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, num);
        return startDT.getTime();
    }
} 
【注意:在web.xml文件中添加如下配置信息代码】
  <!-- begin 定时任务管理器 add by xuqb -->
  <listener>
      <listener-class>com.wisdom.smsframe.logic.smsend.TimerManager</listener-class>
  </listener> 
  <!-- end 定时任务管理器, add by xuqb -->
/***第二个类,配合定时器引入具体业务实现类***/ 
package com.wisdom.smsframe.logic.smsend;
import common.Logger;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
 * Created on      2013-8-13
 * <p>Title:       JavaWeb程序_[定时任务管理器]_[引用类]</p>
 * <p>Description: [配合定时器引入具体业务实现类]</p>
 * <p>Copyright:   xuqb (c) 2013</p>  
 * <p>Company:     xuqb工作室</p>
 * @developer      xuqb[155282323@qq.com]
 * @version        1.0
*/
public class NFDFlightDataTimerTask extends TimerTask 
{
    /**
     * <p>Description:[字段功能描述]</p>  
     * <p>Value:log</p>
     */
    private static Logger log = Logger.getLogger(NFDFlightDataTimerTask.class);
    /**
     *  Created on       2013-8-13
     * <p>Description:   [方法功能中文描述]</p>
     * @developer:       xuqb[155282323@qq.com]
     * @update:          [日期YYYY-MM-DD][更改人姓名][E-mail]
     */
    public void run()
    {
        try
        {
            //在这里写你要执行的内容
            System.out.println("xuqb先生提示:这里编辑您的业务方法");
        }
        catch (Exception emz)
        {
            System.out.println("解析信息发生异常");
            log.info("-------------解析信息发生异常--------------");
            emz.printStackTrace();
        }
    }
    
    /**
     * Created on      2013-8-13
     * <p>Title:       JavaWeb程序_[模块名称]_[说明]</p>
     * <p>Description: [描述该类概要功能介绍]</p>
     * <p>Copyright:   xuqb (c) 2013</p>  
     * <p>Company:     xuqb工作室</p>
     * @developer      xuqb[155282323@qq.com]
     * @version        1.0
    */
    public class NFDFlightDataTaskListener implements ServletContextListener
    {
        /**
         *  Created on       2013-8-13
         * <p>Description:   [方法功能中文描述]</p>
         * @developer:       xuqb[155282323@qq.com]
         * @update:          [日期YYYY-MM-DD][更改人姓名][E-mail]
         */
        public void contextInitialized(ServletContextEvent event)
        {
            new TimerManager();
        }
        /**
         *  Created on       2013-8-13
         * <p>Description:   [方法功能中文描述]</p>
         * @developer:       xuqb[155282323@qq.com]
         * @update:          [日期YYYY-MM-DD][更改人姓名][E-mail]
         */
        public void contextDestroyed(ServletContextEvent event)
        {
        }
    }
}
/***第三个类,读取指定目录下的配置文件内容的类***/
package com.wisdom.base;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;
import java.net.URLDecoder;
/**
 * 这是个配置文件操作类,用来读取和设置ini配置文件
 */
public final class ConfigurationFile
{
 
    public static String getConfigFilePath()
    {
        String str_application_path = "";
        try
        {          
          String str_class_path = 
           ConfigurationFile.class.getClassLoader().getResource("").getPath();
          if (str_class_path == null || str_class_path.trim().equals(""))
           return "";
          str_class_path = URLDecoder.decode(str_class_path, "UTF-8");
          File class_dir = new File(str_class_path);
          String str_webinfo_dir = 
           class_dir.getParentFile().getPath();
          if (!str_webinfo_dir.endsWith(File.separator)) {
           str_webinfo_dir += File.separator;
          }
          str_application_path= str_webinfo_dir + "smcs.ini";
          System.out.println("SMCS Path:" + str_application_path);
        }
        catch (Exception ex)
        {
        }
        return str_application_path;
    }
 
    /**
     * 从ini配置文件中读取变量的值
     * @param file 配置文件的路径
     * @param section 要获取的变量所在段名称
     * @param variable 要获取的变量名称
     * @param defaultValue 变量名称不存在时的默认值
     * @return 变量的值
     * @throws IOException 抛出文件操作可能出现的io异常
     */
    public static String getProfile(
        String file,
        String section,
        String variable,
        String defaultValue) throws IOException
    {
        String strLine, value = "";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        boolean isInSection = false;
        try
        {
            while ( (strLine = bufferedReader.readLine()) != null)
            {
                strLine = strLine.trim();
                //strLine = strLine.split("[;]")[0];
                Pattern p;
                Matcher m;
                p = Pattern.compile("\[\s*.*\s*\]");
                m = p.matcher( (strLine));
                if (m.matches())
                {
                    p = Pattern.compile("\[\s*" + section + "\s*\]");
                    m = p.matcher(strLine);
                    if (m.matches())
                    {
                        isInSection = true;
                    }
                    else
                    {
                        isInSection = false;
                    }
                }
                if (isInSection == true)
                {
                    strLine = strLine.trim();
                    String[] strArray = strLine.split("=");
                    if (strArray.length == 1)
                    {
                        value = strArray[0].trim();
                        if (value.equalsIgnoreCase(variable))
                        {
                            value = "";
                            return value;
                        }
                    }
                    else if (strArray.length == 2)
                    {
                        value = strArray[0].trim();
                        if (value.equalsIgnoreCase(variable))
                        {
                            value = strArray[1].trim();
                            return value;
                        }
                    }
                    else if (strArray.length > 2)
                    {
                        value = strArray[0].trim();
                        if (value.equalsIgnoreCase(variable))
                        {
                            value = strLine.substring(strLine.indexOf("=") + 1).
                                trim();
                            return value;
                        }
                    }
                }
            }
        }
        finally
        {
            bufferedReader.close();
        }
        return defaultValue;
    }
 
    /**
     * 修改ini配置文件中变量的值
     * @param file 配置文件的路径
     * @param section 要修改的变量所在段名称
     * @param variable 要修改的变量名称
     * @param value 变量的新值
     * @throws IOException 抛出文件操作可能出现的io异常
     */
    public static boolean setProfile(
        String file,
        String section,
        String variable,
        String value) throws IOException
    {
        String fileContent, allLine, strLine, newLine, remarkStr;
        String getValue;
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        boolean isInSection = false;
        fileContent = "";
        try
        {
            while ( (allLine = bufferedReader.readLine()) != null)
            {
                allLine = allLine.trim();
                if (allLine.split("[;]").length > 1)
                    remarkStr = ";" + allLine.split(";")[1];
                else
                    remarkStr = "";
                strLine = allLine.split(";")[0];
                Pattern p;
                Matcher m;
                p = Pattern.compile("\[\s*.*\s*\]");
                m = p.matcher( (strLine));
                if (m.matches())
                {
                    p = Pattern.compile("\[\s*" + section + "\s*\]");
                    m = p.matcher(strLine);
                    if (m.matches())
                    {
                        isInSection = true;
                        //isInSection = false;
                    }
                }
                if (isInSection == true)
                {
                    strLine = strLine.trim();
                    String[] strArray = strLine.split("=");
                    getValue = strArray[0].trim();
                    if (getValue.equalsIgnoreCase(variable))
                    {
                        newLine = getValue + "=" + value;
                        fileContent += newLine + "
";
                        while ( (allLine = bufferedReader.readLine()) != null)
                        {
                            fileContent += allLine + "
";
                        }
                        bufferedReader.close();
                        BufferedWriter bufferedWriter =
                            new BufferedWriter(new FileWriter(file, false));
                        bufferedWriter.write(fileContent);
                        bufferedWriter.flush();
                        bufferedWriter.close();
                        return true;
                    }
                }
                fileContent += allLine + "
";
            }
        }
        catch (IOException ex)
        {
            throw ex;
        }
        finally
        {
            bufferedReader.close();
        }
        return false;
    }
} 
=*=*=*=*=*=*=*=*==关于配置文件的编辑说明=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
smcs.ini配置文件中写如下代码即可:
[dsrwtime]
mytimer = 15:45


 

原文地址:https://www.cnblogs.com/hzcya1995/p/13318183.html