asp.net 线程 (单)

public class Global : System.Web.HttpApplication
    {
        public System.Threading.Thread schedulerThread = null;
        public void Task()
        {
            var config = new TaskScheduler.SchedulerConfiguration(1000 *60*15);
            config.Jobs.Add(new TaskScheduler.Method1());
            config.Jobs.Add(new TaskScheduler.Method2());
            var scheduler = new TaskScheduler.Scheduler(config);
            var myThreadStart = new System.Threading.ThreadStart(scheduler.Start);
            var schedulerThread = new System.Threading.Thread(myThreadStart);
            schedulerThread.Start();
        }
        protected void Application_Start(object sender, EventArgs e)
        {
            Task();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            //System.Threading.Thread.Sleep(1000);
            //string url = "";
            //System.Net.HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            //System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
            //Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
          
            if (null != schedulerThread)
            {
                schedulerThread.Abort();
            }
           // System.Threading.Thread.Sleep(1000);
           // string url = "";
           // System.Net.HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
           // System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
           //Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流
        }
    }

程序启动时调用线程;

  public partial class TaskScheduler
    {
        /// <summary>
        /// 执行方法接口
        /// </summary>
        public interface ISchedulerJob
        {
            /// <summary>
            /// 执行方法
            /// </summary>
            void Execute();
        }
        public static string MapPath(string strPath)  
{  
    if (System.Web.HttpContext.Current != null)  
    {  
        return System.Web.HttpContext.Current.Server.MapPath(strPath);  
    }  
    else //非web程序引用   
    {  
        strPath = strPath.Replace("/", "");  
        strPath = strPath.Replace("~","");  
        if (strPath.StartsWith("//"))  
        {  
            strPath = strPath.TrimStart('/');  
        }  
        return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);  
    }  
        }
        /// <summary>
        /// 任务sample1
        /// </summary>
        public class Method1 : ISchedulerJob
        {
            public void Execute()
            {
                //需要定时执行的方法1
                //文件保存的物理路径,CSTest为虚拟目录名称,F:/Inetpub/wwwroot/CSTest为物理路径                    
                //string p = System.Web.HttpContext.Current.Server.MapPath("../"); 

                string p = MapPath("/");
                //我们在虚拟目录的根目录下建立SchedulerJob文件夹,并设置权限为匿名可修改,    
                //SchedulerJob.txt就是我们所写的文件    
                string FILE_NAME = p + "XTGL/SchedulerJob.txt";
                //取得当前服务器时间,并转换成字符串    
                string c = System.DateTime.Now.ToString();
                //标记是否是新建文件的标量    
                bool flag = false;
                //如果文件不存在,就新建该文件    
                if (!File.Exists(FILE_NAME))
                {
                    flag = true;
                   
                    StreamWriter sr = File.CreateText(FILE_NAME);
                    sr.Close();
                }


                DateTime data = Convert.ToDateTime("23:40");
                DateTime dataNow = Convert.ToDateTime(System.DateTime.Now);
                TimeSpan ts = dataNow - data;
                //时间差的绝对值
                String spanTime = ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "" + ts.Seconds.ToString() + "";
               TimeSpan ts1= ts.Duration();
               Double spanTime1 = ts1.TotalMinutes;
                if (spanTime1 < 7.5 )
                //向文件写入内容  
                {
                    StreamWriter x = new StreamWriter(FILE_NAME, true, System.Text.Encoding.Default);
                    if (flag) x.Write("计划任务测试开始:");
                    x.Write("/r/n" + c + "正常计算平均值("+spanTime1+")");

                    x.Close();
                    pjfInit();
                }
                else
                {
                    StreamWriter x = new StreamWriter(FILE_NAME, true, System.Text.Encoding.Default);
                    if (flag) x.Write("计划任务测试开始:");
                    x.Write("/r/n" + c + "时间未到,线程正常,任务准备中(" + spanTime1 + ")");

                    x.Close();
                }
                
            }
        }
        /// <summary>
        /// 任务sample2
        /// </summary>
        public class Method2 : ISchedulerJob
        {
            public void Execute()
            {
                //需要定时执行的方法2
            }
        }
        // 接下来,我们建立一个配置对象,告诉调度引擎执行什么任务和执行的时间间隔。
        /// <summary>
        /// 
        /// </summary>
        public class SchedulerConfiguration
        {
            //时间间隔
            //任务列表
            /// <summary>
            /// 
            /// </summary>
            private readonly ArrayList jobs = new ArrayList();

            /// <summary>
            /// 线程睡眠时间设置
            /// </summary>
            /// <value>The sleep interval.</value>
            public int SleepInterval { get; private set; }

            /// <summary>
            /// 需完成的工作列表
            /// </summary>
            /// <value>The jobs.</value>
            public ArrayList Jobs { get { return jobs; } }

            public SchedulerConfiguration(int newSleepInterval)
            {
                SleepInterval = newSleepInterval;
            }
        }
        public static void pjfInit()
        {
            Sab_hhb_zhb ZHB = new Sab_hhb_zhb();
            Sab_hhb_sfcj_pj sfcj = new Sab_hhb_sfcj_pj();
            Sab_hhB_sfcjtype sfcjType = new Sab_hhB_sfcjtype();
            Sab_hhb_gzpj_pj gzpj = new Sab_hhb_gzpj_pj();
            Sab_hhb_gfpj_pj gfpj = new Sab_hhb_gfpj_pj();
            Sab_hhb_pfbz pfbz = new Sab_hhb_pfbz();
            jgdx jgDal = new jgdx();
            List<jgdxDS> jgModel = jgDal.GetModelList("(isdelete=0 or isdelete is null)");
            for (int i = 0; i < jgModel.Count; i++)
            {
                #region  ExtensionMethod
                //综合榜算法,现根据mid查新公众评价,官方评价,示范创建的得分情况
                //再跟评分标准中的比例进行计算

                DataSet ds = ZHB.GetList("mid='" + jgModel[i].mid + "'");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    int gzdf = 0, gfdf = 0, sfdf = 0;
                    int id = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["id"].ToString());
                    Sab_hhb_zhbDS zhbmodel = ZHB.GetModel(id);
                    DataSet gfpjds = gfpj.GetList("mid='" + jgModel[i].mid + "'");
                    if (gfpjds.Tables[0].Rows.Count > 0)
                    {
                        gfdf = ConvertHelper.GetInteger(gfpjds.Tables[0].Rows[0]["Pjdf"].ToString());
                    }

                    DataSet gzpjds = gzpj.GetList("mid='" + jgModel[i].mid + "'");
                    if (gzpjds.Tables[0].Rows.Count > 0)
                    {
                        gzdf = ConvertHelper.GetInteger(gzpjds.Tables[0].Rows[0]["pjdf"].ToString());
                    }

                    DataSet sfcjds = sfcj.GetList("mid='" + jgModel[i].mid + "'");
                    if (sfcjds.Tables[0].Rows.Count > 0)
                    {
                        int sfcjTypeID = ConvertHelper.GetInteger(sfcjds.Tables[0].Rows[0]["pjjbID"].ToString());
                        Sab_hhB_sfcjtypeDS sfcjTypemodel = sfcjType.GetModel(sfcjTypeID);
                        sfdf = sfcjTypemodel.pjdf;
                    }


                    //评分标准算法
                    DataSet pfbzds = pfbz.GetList("LeiMing='评分标准'");
                    int Zdf;
                    if (pfbzds.Tables[0].Rows.Count > 0)
                    {
                        int ID = ConvertHelper.GetInteger(pfbzds.Tables[0].Rows[0]["ID"].ToString());
                        Sab_hhb_pfbzDS model = pfbz.GetModel(ID);

                        Zdf = (gfdf * model.gfpjBiLi + gzdf * model.gzpjBiLi + sfdf * model.sfcjBiLi) / 100;
                    }
                    else
                    {
                        Zdf = (gzdf + gfdf + sfdf) / 3;
                    }
                    if (zhbmodel.pjdf > Zdf)
                    {
                        zhbmodel.pjqs = 0;
                    }
                    if (zhbmodel.pjdf == Zdf)
                    {
                        zhbmodel.pjqs = 1;
                    }
                    if (zhbmodel.pjdf < Zdf)
                    {
                        zhbmodel.pjqs = 2;
                    }

                    zhbmodel.pjdf = Zdf;
                    zhbmodel.isDelete = 0;
                    ZHB.Update(zhbmodel);
                }
                else
                {
                    int gzdf = 0, gfdf = 0, sfdf = 0;
                    Sab_hhb_zhbDS model = new Sab_hhb_zhbDS();
                    DataSet gfpjds = gfpj.GetList("mid='" + jgModel[i].mid + "'");
                    if (gfpjds.Tables[0].Rows.Count > 0)
                    {
                        gfdf = ConvertHelper.GetInteger(gfpjds.Tables[0].Rows[0]["Pjdf"].ToString());
                    }

                    DataSet gzpjds = gzpj.GetList("mid='" + jgModel[i].mid + "'");
                    if (gzpjds.Tables[0].Rows.Count > 0)
                    {
                        gzdf = ConvertHelper.GetInteger(gzpjds.Tables[0].Rows[0]["pjdf"].ToString());
                    }

                    DataSet sfcjds = sfcj.GetList("mid='" + jgModel[i].mid + "'");
                    if (sfcjds.Tables[0].Rows.Count > 0)
                    {
                        int sfcjTypeID = ConvertHelper.GetInteger(sfcjds.Tables[0].Rows[0]["pjjbID"].ToString());
                        Sab_hhB_sfcjtypeDS sfcjTypemodel = sfcjType.GetModel(sfcjTypeID);
                        sfdf = sfcjTypemodel.pjdf;
                    }

                    //评分标准算法
                    DataSet pfbzds = pfbz.GetList("LeiMing='评分标准'");
                    int Zdf;
                    if (pfbzds.Tables[0].Rows.Count > 0)
                    {
                        int ID = ConvertHelper.GetInteger(pfbzds.Tables[0].Rows[0]["ID"].ToString());
                        Sab_hhb_pfbzDS modelpfbz = pfbz.GetModel(ID);

                        Zdf = (gfdf * modelpfbz.gfpjBiLi + gzdf * modelpfbz.gzpjBiLi + sfdf * modelpfbz.sfcjBiLi) / 100;
                    }
                    else
                    {
                        Zdf = (gzdf + gfdf + sfdf) / 3;
                    }
                    model.pjqs = 1;
                    model.pjdf = Zdf;
                    model.isDelete = 0;
                    model.mid = jgModel[i].mid;
                    ZHB.Add(model);
                }
                #endregion  ExtensionMethod
            }

        }
        //下面就是调度引擎,定时执行配置对象的任务
        /// <summary>
        /// 
        /// </summary>
        public class Scheduler
        {
            /// <summary>
            /// 
            /// </summary>
            private readonly SchedulerConfiguration configuration;

            /// <summary>
            /// Initializes a new instance of the <see cref="Scheduler"/> class.
            /// </summary>
            /// <param name="config">The config.</param>
            public Scheduler(SchedulerConfiguration config)
            {
                configuration = config;
            }

            /// <summary>
            /// Starts this instance.
            /// </summary>
            public void Start()
            {
                while (true)
                {
                    //执行每一个任务
                    foreach (ISchedulerJob job in configuration.Jobs)
                    {
                        var myThreadDelegate = new ThreadStart(job.Execute);
                        var myThread = new Thread(myThreadDelegate);
                        myThread.Start();
                    }
                    Thread.Sleep(configuration.SleepInterval);
                }
            }
           
        }
    }

线程方法;技术不深,暂时不知有何问题,记录下自己查看,有高人请指导。

posted @ 2017-02-18 17:28  net开发人员  阅读(1012)  评论(0编辑  收藏  举报