C#利用定时任务插件实现在后台线程中批量把动态文件生成静态文件方法

来源:互联网 发布:js 自动触发点击事件 编辑:程序博客网 时间:2024/05/08 07:05

global.asax实现:”

static QuartzWorker worker;protected void Application_Start(Object sender, EventArgs e){                      worker = new QuartzWorker();NewsUpdateWork newsWork = new NewsUpdateWork(); worker.AddWork(newsWork); worker.Start();   }

protected void Application_End(Object sender, EventArgs e){//在应用程序关闭时运行的代码if (worker != null){worker.Stop();}}

NewsUpdateWork.cs实现:

public class NewsUpdateWork : QuartzJob    {        public NewsUpdateWork()        {            //CronExpression = "0 0/1 * * * ?";            //每天21点-24点,0点-7点,每隔5分钟执行一次            //CronExpression = "0 0/5 18-23,0-9 * * ?";            CronExpression = "0 0/5 * * * ?";            RepeatInterval = new TimeSpan(0, 0, 0);            RepeatCount = 0;            DoWork += new EventHandler(this_DoWork);        }        public void this_DoWork(object sender, EventArgs e)        {            News news = new News();            news.BatCreateNewsHtml();        }    }

BatCreateNewsHtml方法:

 /// <summary>        /// 批量创建网页        /// </summary>        public void BatCreateNewsHtml()        {            //循环更新设置为还未生成静态新闻的新闻,一次生成200条新闻。每5分钟执行一次            DataTable dt = facade.GetNewsIdList();            for (int i = 0; i < dt.Rows.Count; i++)            {                try                {                    int id = Convert.ToInt32(dt.Rows[i]["news_id"].ToString());                    //EventLog.WriteLog("生成开始" + id.ToString());                    //生成静态文件                    CreateHtml(id);                    //更新静态文件是否更新字段为1,表示静态文件已经重新生成                    UpdateIsUpdate(id);                    //EventLog.WriteLog("生成结束" + id.ToString());                }                catch (Exception ex)                {                    EventLog.WriteLog(ex.Source + "\n" + ex.Message + "\n" + ex.StackTrace);                    return;                }            }        }

CreateHtml方法的实现:

public void CreateHtml(int id)        {            string oldfile;            string newfile;            DataTable dt = facade.GetNewsTypeList(id);            if (dt.Rows.Count <= 0)            {                return;            }            switch (dt.Rows[0]["News_type"].ToString())            {                case "10":                                    oldfile = ApplicationSettings.Get("WebDomain") + "/newshtml/showcy.asp?rec=" + id.ToString();                    newfile = "/newshtml/" + dt.Rows[0]["htmlurl"].ToString();                                     CreateFile.CreateHtml(oldfile, newfile);                    break;                //如果是法律法规标签,不生成静态文件                case "5":                                case "88":                    //do nothing                     break;                default:                    oldfile = ApplicationSettings.Get("WebDomain") + "/newshtml/shownews.asp?rec=" + id.ToString();                    newfile = "/newshtml/" + dt.Rows[0]["htmlurl"].ToString();                    CreateFile.CreateHtml(oldfile, newfile);                    break;            }        }

CreateFile.CreateHtml方法实现:

public static void CreateHtml(string webUrl, string htmlPath)        {            CreateHtml(webUrl, htmlPath, Encoding.GetEncoding("gb2312"));        } public static void CreateHtml(string webUrl, string htmlPath, Encoding encoding)        {            CreateHtml(webUrl, htmlPath, encoding, encoding);        }public static void CreateHtml(string webUrl, string htmlPath, Encoding readEncoding, Encoding writeEncoding)        {            string newPageHtml = "";            //虚拟路径            string PageUrl = "";            newPageHtml = TextUtility.GetRealPath(htmlPath);            //EventLog.WriteLog(newPageHtml);            PageUrl = webUrl;            try            {                WebRequest request = WebRequest.Create(webUrl);                WebResponse response = request.GetResponse();                using (Stream stream = response.GetResponseStream())                {                    using (StreamReader reader = new StreamReader(stream, readEncoding))                    {                        //从动态文件中读取html代码                        string tem = reader.ReadToEnd();                        string physicalPath = newPageHtml;                        FileManager.CreateFolder(physicalPath);                        //如果文件不存在,则创建                        if (!FileManager.Exists(physicalPath, FsoMethod.File))                        {                                                        FileManager.Create(physicalPath, FsoMethod.File);                        }                        //把读取的内容写入相应的html文件                        FileManager.WriteFile(physicalPath, tem, writeEncoding);                    }                }            }            catch (Exception e)            {                //捕获异常后的处理代码                 EventLog.WriteLog(e.Source + "\n" + e.Message + "\n" + e.StackTrace);                return;            }        }

获取真实路径方法:

public static string GetRealPath( string strPath )        {            if ( string.IsNullOrEmpty( strPath ) )            {                throw new Exception( "strPath 不能为空!" );            }            HttpContext current = null;            try            {                current = HttpContext.Current;            }            catch            {                current = null;            }            if ( current != null )            {                return current.Server.MapPath( strPath );            }            string str2 = Path.Combine( strPath , "" );            str2 = str2.StartsWith( @"\\" ) ? str2.Remove( 0 , 2 ) : str2;            return ( AppDomain.CurrentDomain.BaseDirectory + Path.Combine( strPath , "" ) );        }

FileManager类中的三个方法:

 /// <summary>        /// 检查目录并创建,如果目录不存在则创建,可创建多个目录        /// </summary>        /// <param name="path">物理路径</param>        public static void CreateFolder(string physicsPath)        {            //如果路径中有文件名,则去除,因为不去除则文件名也会创建为一个文件夹            if (GetFileName(physicsPath).IsNotNullAndEmpty())            {                physicsPath = physicsPath.Replace(GetFileName(physicsPath), "");            }            string folder = "";            string[] arry = physicsPath.Split('\\');            for (int i = 0; i < arry.Length; i++)            {                folder += arry[i] + "\\";                if (!Directory.Exists(folder))                    Directory.CreateDirectory(folder);            }        }

/// <summary>        /// 新建单个文件或文件夹        /// </summary>        /// <param name="file">文件或文件夹及其路径</param>        /// <param name="method">新建方式</param>        public static void Create(string file, FsoMethod method)        {            try            {                if (method == FsoMethod.File)                {                    WriteFile(file, "");                }                else if (method == FsoMethod.Folder)                {                    Directory.CreateDirectory(file);                }            }            catch (Exception exception)            {                throw new Exception(exception.ToString());            }        }

/// <summary>        ///  以文件流的形式将内容写入到指定文件中(如果该文件或文件夹不存在则创建)        ///   默认是带签名的 UTF8        /// </summary>        /// <param name="file">文件名和指定路径</param>        /// <param name="fileContent">文件内容</param>        /// <param name="encoding">文件编码 缺省 UTF-8</param>        public static void WriteFile(string file, string fileContent, Encoding encoding)        {            FileInfo info = new FileInfo(file);            if (!Directory.Exists(info.DirectoryName))            {                Directory.CreateDirectory(info.DirectoryName);            }            FileStream stream = new FileStream(file, FileMode.Create, FileAccess.Write);            StreamWriter writer = new StreamWriter(stream, encoding);            try            {                writer.Write(fileContent);            }            catch (Exception exception)            {                throw new Exception(exception.ToString());            }            finally            {                writer.Flush();                stream.Flush();                writer.Close();                stream.Close();            }        }


 
阅读全文
0 0
原创粉丝点击