当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > 利用Timer在ASP.NET中实现计划任务的方法

ASP.NET
ASP.NET FORUMS换肤流程
关于webservice的异步调用简单实例
nhibernate数据加载之Criteria加载
C# 把指定控件显示在最上面
VB面向对象编程的一个简单的演示程序
关于如何利用COM+,来提高ASP执行权限的问题!
ASP.NET跨应用程序进行登录的解决
在快捷方式的右键菜单上添加打开所在目录的菜单项
XML简明教程(一)
使用自定义的数据源进行DataGrid控件的数据绑定
提供两种散列加密算法:MD5、SHA1。大小写敏感
把鼠标放在Form的边缘上不会出现可拉动
The custom tool 'CrystalDecisions.VSDesigner.CodeGen.ReportCodeGenerator' failed
Split的用法
利用XSD生成強類型類文件和描述文件
关于datagrid中的字符串转换
C#中来应用Hook
Get your Crystal report working on your customers server (Cannot find Keycod...
C#中如何插入照片到Excel
.net中Web自定义控件编写注意事项

利用Timer在ASP.NET中实现计划任务的方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 110 ::
收藏到网摘: n/a

.NET Framework中为我们提供了3种类型的Timer,分别是:
Server Timer(System.Timers.Timer),Thread Timer(System.Threading.Timer )和Windows Timer(System.Windows.Forms.Timer)。
其中Windows Timer和WinAPI中的Timer一样,是基于消息的,而且是单线程的。另外两个Timer则不同于Windows Timer,它们是基于ThreadPool的,这样最大的好处就是,产生的时间间隔准确均匀。Server Timer和Thread Timer的区别在于,Server Timer是基于事件的,而Thread Timer是基于Callback的。
相比之下Thread Timer更轻量级一些,所以下文主要以Thread Timer为例,讲解如何利用Thread Timer在ASP.NET中实现计划任务。
下面给出一个用Timer实现计划任务的类:
public class ScheduledTask
{
private static readonly ScheduledTask _ScheduledTask = null;
private Timer UpdateTimer = null;
//间隔时间,这里设置为15分钟
private int Interval = 15 * 60000;
private int _IsRunning;
static ScheduledTask()
{
_ScheduledTask = new ScheduledTask();
}
public static ScheduledTask Instance()
{
return _ScheduledTask;
}
public void Start()
{
if(UpdateTimer == null)
{
UpdateTimer = new Timer(new TimerCallback(UpdateTimerCallback), null, Interval, Interval);
}
}
private void UpdateTimerCallback(object sender)
{
if(Interlocked.Exchange(ref _IsRunning, 1) == 0)
{
try
{
//此处写你自己想执行的任务
}
catch(Exception ex)
{
}
finally
{
Interlocked.Exchange(ref _IsRunning, 0);
}
}
}
public void Stop()
{
if(UpdateTimer != null)
{
UpdateTimer.Dispose();
UpdateTimer = null;
}
}
}
首先,注意一下这段:private int _IsRunning;
_IsRunning是一个标志,它代表上一个时间间隔触发的任务是否运行完成。
为什么我们需要这个_IsRunning标志呢?
因为,如果我们执行的任务时间很长,就可能造成上一个时间段触发的任务还没有执行完成,下一个任务又开始了,这样就会造成重入的问题。为了解决这个问题,我们用_IsRunning作为一个标志,表示上次的任务是否完成了,如果完成了,我们就执行新的任务,如果没完成就跳过这次的任务继续执行上次的任务。
具体的逻辑在下面这段代码中实现:
程序代码
private void UpdateTimerCallback(object sender)
{
if(Interlocked.Exchange(ref _IsRunning, 1) == 0)
{
try
{
//此处写你自己想执行的任务
}
catch(Exception ex)
{
}
finally
{
Interlocked.Exchange(ref _IsRunning, 0);
}
}
}
大家看到,上面代码中用到了Interlocked.Exchange这个方法。该方法的作用是保证多线程下给对象赋值的安全性。因为在多线程下,我们直接给_IsRunning赋值是不安全的,所以在这种情况下Interlocked.Exchange就派上了用场。
说完了ScheduledTask类的实现,下面我们看看如何在ASP.NET中调用这个类。
建议在Application_Start中调用这个类,代码如下:
程序代码
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
ScheduledTask.Instance().Start();
}
protected void Application_End(object sender, EventArgs e)
{
ScheduledTask.Instance().Stop();
}
}
OK,以上就是Timer在ASP.NET中的简单应用,如果有什么说的不对的地方,还请多多指教。