天山彤佬

超级软件测试工程师

博客园 首页 新随笔 联系 订阅 管理

asp.net程序一般是当用户请求一个Page,或者请求一个WebService的时候,才会执行一段代码,如果我们希望让程序定时自动执行代码,但是又不增加新的应用程序,应该怎么做呢?

首先,给你的web应用程序,添加一个“Global.asax”文件,这个类里面默认有一个“Application_Start”,我们就在这个方法里面添加定时程序的逻辑代码。这样,只要有一个人访问了这个web应用,就会启动这个定时程序。

为了方便我们对定时程序的管理,我们单独编写一个类,专门用于控制定时程序。这个类中用的核心对象是System.Timers.Timer。下面说一下这个类设计的基本思路:ExecuteTask是一个公共的事件对象,以后调用者可以利用它来添加回调函数。_task是这个类型的唯一静态实例,调用者可以用Instance()方法读取它。_timer就是实现定时运行的对象,Interval是运行的间隔时间。

 

public class Time_Task
{
    public event System.Timers.ElapsedEventHandler ExecuteTask;

    private static readonly Time_Task _task = null;
    private System.Timers.Timer _timer = null;
    private int _interval = 1000;

    public int Interval
    {
        set
        {
            _interval = value;
        }
        get
        {
            return _interval;
        }
    }
    
    static Time_Task()
    {
        _task = new Time_Task();
    }
    
    public static Time_Task Instance()
    {
        return _task;
    }
    
    public void Start()
    {
        if(_timer == null)
        {
            _timer = new System.Timers.Timer(_interval);
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
            _timer.Enabled = true;
            _timer.Start();
        }
    }
    
    protected void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        if(null != ExecuteTask)
        {
            ExecuteTask(sender, e);
        }
    }
    
    public void Stop()
    {
        if(_timer != null)
        {
            _timer.Stop();
            _timer.Dispose();
            _timer = null;
        }
    }
}

 

有了这个类型,我们可以在Application_Start方法中轻松的实现定时了。

 

protected void Application_Start(object sender, EventArgs e)
{
    Time_Task.Instance().ExecuteTask += new System.Timers.ElapsedEventHandler(Global_ExecuteTask);
    Time_Task.Instance().Interval = 1000 * 60;//表示间隔1分钟
    Time_Task.Instance().Start();
}

void Global_ExecuteTask(object sender, System.Timers.ElapsedEventArgs e)
{
    //在这里编写需要定时执行的逻辑代码
}

 

需要注意的是,当你重新部署web应用的时候,比如更新了DLL文件,或者修改了web.config文件,就会中止这个定时程序,需要有人再次请求Page,才能把它启动起来。

posted on 2009-03-13 00:05  陈逊  阅读(4807)  评论(0编辑  收藏  举报