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)
{
    //在这里编写需要定时执行的逻辑代码
}


http://telescope.blog.163.com/blog/static/370819502010610111551845/?latestBlog

 posted on 2010-07-21 12:02  ddxgc  阅读(1129)  评论(0编辑  收藏  举报