您的位置:首页 > 编程语言 > ASP

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

2011-11-01 12:20 826 查看
 
在asp.net中要不使用其他插件的情况下只能使用定时器来检查, 并执行任务.

以下讲解步骤:

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

view sourceprint?

01
void
Application_Start(
object
sender, EventArgs e) 
02
{
03
    
// 在应用程序启动时运行的代码
04
    
//定义定时器
05
    
//1000表示1秒的意思
06
    
System.Timers.Timer myTimer =
new

System.Timers.Timer(1000);
07
    
//TaskAction.SetContent表示要调用的方法
08
    
myTimer.Elapsed +=
new

System.Timers.ElapsedEventHandler(TaskAction.SetContent);
09
    
myTimer.Enabled =
true
;
10
    
myTimer.AutoReset =
true
11
}
Application_Start 只有在访问一次之后才会触发.

 

view sourceprint?

01
void
Session_End(
object
sender, EventArgs e) 
02
{
03
    
//下面的代码是关键,可解决IIS应用程序池自动回收的问题
04
    
System.Threading.Thread.Sleep(1000);
05
    
//触发事件, 写入提示信息
06
    
TaskAction.SetContent();
07
    
//这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start 
08
    
//使用您自己的URL
09
    
string
url =
"http://henw.cnblog.com"
;
10
    
System.Net.HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
11
    
System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
12
    
System.IO.Stream receiveStream = myHttpWebResponse.GetResponseStream();
//得到回写的字节流
13
 
 
14
    
// 在会话结束时运行的代码。 
15
    
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 InProc 时,才会引发 Session_End 事件。
16
    
// 如果会话模式设置为 StateServer 
17
    
// 或 SQLServer,则不会引发该事件。
18
}
Session_End 中的方法主要是解决IIS应用程序池自动回收的问题.

 

2. 添加计划任务类 TaskAction

view sourceprint?

01
using
System;
02
using
System.Collections.Generic;
03
using
System.Linq;
04
using
System.Web;
05
using
System.Timers;
06
 
 
07
/// <summary>
08
///Action 的摘要说明
09
/// </summary>
10
public
static
class
TaskAction
11
{
12
    
private
static

string
content =

""
;
13
    
/// <summary>
14
    
/// 输出信息存储的地方.
15
    
/// </summary>
16
    
public
static

string
Content

17
    
{

18
        
get
{
return
TaskAction.content; }
19
        
set
{TaskAction.content +=
"<div>"
+ value+
"</div>"
; }
20
    
}

21
    
/// <summary>
22
    
/// 定时器委托任务 调用的方法
23
    
/// </summary>
24
    
/// <param name="source"></param>
25
    
/// <param name="e"></param>
26
    
public
static

void
SetContent(
object
source, ElapsedEventArgs e)
27
    
{

28
        
Content= DateTime.Now.ToString(
"yyyy-MM-dd HH:mm:ss"
);
29
    
}

30
    
/// <summary>
31
    
/// 应用池回收的时候调用的方法
32
    
/// </summary>
33
    
public
static

void
SetContent()

34
    
{

35
        
Content=
"END: "

+ DateTime.Now.ToString(
"yyyy-MM-dd HH:mm:ss"
);
36
    
}

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

view sourceprint?

1
<
div
>
2
    
<%=TaskAction.Content%>
3
</
div
>
 

4. 结果输出





欢迎大家一起探讨

示例源代码下载

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息