5

.Net Global.asax实现定时任务

 2 years ago
source link: https://www.fengxianqi.com/index.php/archives/24/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

.Net Global.asax实现定时任务

定时任务,比如定时检测工单是否超时,定时发送短信等。类似JavaScript中的setTimeout。.Net中是可以用global.asax做到的。

先来看看自动生成的Global文件的内容

<%@ Application Language="C#" %>

<script RunAt="server">

    void Application_Start(object sender, EventArgs e)
    {
        // 在应用程序启动时运行的代码  
    }

    void Application_End(object sender, EventArgs e)
    {


    }

    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>

在Application_Start添加定时器,以及在同级的作用域声明定时执行的方法

 void Application_Start(object sender, EventArgs e)
    {
        // 在应用程序启动时运行的代码  

        //每十分钟检测一次
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Enabled = true;
        timer.Interval = 600000; //执行间隔时间,单位为毫秒; 这里实际间隔为10分钟  
        timer.Start();
        timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);

    }
  private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
    {
        //do something
    }

1.当程序启动,会立即访问Application_Start,因此定时器就开始执行了。
2.当程序长时间没有动作,或者说这个网站长时间没有人访问, ,导致定时器不再执行,一般是1个小时或者2个小时吧。也就是说定时任务执行了一段时间就不再执行了。

解决IIS应用程序池自动回收的问题

1.既然在一段时间后会回收,我们就可以在回收的时候自动访问一下网站,重新启动程序。上面Global.asax文件可以看到还有一个Application_End事件,当程序结束时就会触发这个事件,因此我们可以在这里设置自动访问网站,这样程序就又开始了。

  void Application_End(object sender, EventArgs e)
    {
        //  在应用程序关闭时运行的代码
     
        //下面的代码是关键,可解决IIS应用程序池自动回收的问题  

        System.Threading.Thread.Sleep(1000);

        //这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start  

        string url = "http://test.com/";

        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();//得到回写的字节流  
    }

「一键投喂 软糖/蛋糕/布丁/牛奶/冰阔乐!」

版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK