ASP.NET MVC 计划任务(不使用外接程序,.net内部机制实现)

在asp.net中要不使用其他插件的情况下只能使用定时器来检查, 并执行任务.

以下讲解步骤:

1. 在Global.asax 文件中作如下修改

 

1
2
3
4
5
6
7
8
9
10
11
void Application_Start(object sender, EventArgs e)
{
    // 在应用程序启动时运行的代码
    //定义定时器
    //1000表示1秒的意思
    System.Timers.Timer myTimer = new System.Timers.Timer(1000);
    //TaskAction.SetContent 表示要调用的方法
    myTimer.Elapsed += new System.Timers.ElapsedEventHandler(TaskAction.SetContent);
    myTimer.Enabled = true;
    myTimer.AutoReset = true;
}

 

Application_Start 只有在访问一次之后才会触发.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void Session_End(object sender, EventArgs e)
{
    //下面的代码是关键,可解决IIS应用程序池自动回收的问题
    System.Threading.Thread.Sleep(1000);
    //触发事件, 写入提示信息
    TaskAction.SetContent();
    //这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start
    //使用您自己的URL
    string url = "http://henw.cnblog.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();//得到回写的字节流
 
    // 在会话结束时运行的代码。
    // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 InProc 时,才会引发 Session_End 事件。
    // 如果会话模式设置为 StateServer
    // 或 SQLServer,则不会引发该事件。
}

 

Session_End 中的方法主要是解决IIS应用程序池自动回收的问题.

 

2. 添加计划任务类 TaskAction

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;
 
/// <summary>
///Action 的摘要说明
/// </summary>
public static class TaskAction
{
    private static string content = "";
    /// <summary>
    /// 输出信息存储的地方.
    /// </summary>
    public static string Content
    {
        get { return TaskAction.content; }
        set { TaskAction.content += "<div>" + value+"</div>"; }
    }
    /// <summary>
    /// 定时器委托任务 调用的方法
    /// </summary>
    /// <param name="source"></param>
    /// <param name="e"></param>
    public static void SetContent(object source, ElapsedEventArgs e)
    {
        Content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    }
    /// <summary>
    /// 应用池回收的时候调用的方法
    /// </summary>
    public static void SetContent()
    {
        Content = "END: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    }
}

 

 

3. 执行结果输出[Default.aspx] (此步仅仅为了观看结果才写的页面) 
在Default.aspx页面 添加

 

<div>
	<%=TaskAction.Content %>
</div>

 

 

4. 结果输出

QQ截图20110923145356

欢迎大家一起探讨

示例源代码下载

posted @ 2014-03-17 15:51  AIの海雅  阅读(406)  评论(0编辑  收藏  举报