网站定时运行源码

在Global.asax文件加一下代码

<%@ Application Language="C#" %>
<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        // 在应用程序启动时运行的代码
        System.Timers.Timer myTimer = new System.Timers.Timer(1000);//修改时间间隔
        //关联事件
        myTimer.Elapsed += new System.Timers.ElapsedEventHandler(mess);
        myTimer.AutoReset = true;

        //系统初始化代码
        Application.Lock();
        Application["autoRunCount"] = 0;
        Application["lastStart"] = DateTime.Now.ToString();
        Application.UnLock();
        myTimer.Enabled = true;
        //在此添加其它代码
    }
    private void mess(object sender,System.Timers.ElapsedEventArgs e)
    {
        //获取当前时间
        Application.Lock();
        if (Convert.ToInt32(Application["autoRunCount"]) < 99999999)
            Application["autoRunCount"] = Convert.ToInt32(Application["autoRunCount"]) + 1;
        else
            Application["autoRunCount"] = 0;
        Application.UnLock();
        //在这写要执行的代码
        //GlobalVar.sendMyMail();
        //设置提醒
    }
    void Application_End(object sender, EventArgs e) 
    {
        //  在应用程序关闭时运行的代码


        //如果出错,删除下面代码
        //下面的代码是关键,可解决IIS应用程序池自动回收的问题
        System.Threading.Thread.Sleep(1000);
        ////这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start
        string url = "http://localhost:82/111.aspx";
        System.Net.HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
        System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
        System.IO.Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流

        //在此添加其它代码
    }
        
    void Application_Error(object sender, EventArgs e)
    { 
        // 在出现未处理的错误时运行的代码

    }

    void Session_Start(object sender, EventArgs e) 
    {
        // 在新会话启动时运行的代码
    }

    void Session_End(object sender, EventArgs e) 
    {
        // 在会话结束时运行的代码。 
        // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
        // InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer 
        // 或 SQLServer,则不会引发该事件。
    }
       
</script>

 

posted @ 2016-03-09 23:52  microsoftzhcn  阅读(384)  评论(0编辑  收藏  举报