清风的blog 优然探索

Asp.Net定时执行计划1

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Web.inc
{
    public class Time_Task
    {
        public event System.Timers.ElapsedEventHandler ExecuteTask;

    /// <summary>
    /// 是否启动了定时执行
    /// </summary>
    public static bool state = false;

    //一下两个静态变量时用于检测定时执行效果的
    public static int i = 1;
    public static int ii = 10;

    private static readonly Time_Task _task = null;

    private System.Timers.Timer _timer = null;

    // 执行的时间间隔 目前设置时60秒 程序在运行的时候最好设置1小时=60*60*1000
    private int _interval = 60*1000;   


    /// <summary>
    /// 定时执行的间隔时间(毫秒)
    /// </summary>
    public int Interval
    {

        set
        {

            _interval = value;

        }

        get
        {

            return _interval;

        }

    }


    static Time_Task()
    {

        _task = new Time_Task();

    }


    /// <summary>
    /// 得到定时执行类的对象
    /// </summary>
    /// <returns></returns>
    public static Time_Task Instance()
    {

        return _task;

    }


    /// <summary>
    /// 开始事件的定时执行
    /// </summary>
    public void Start()
    {

        if (_timer == null)
        {

            _timer = new System.Timers.Timer(_interval);

            _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);

            _timer.Enabled = true;
            state = true;
            _timer.Start();

        }

    }


   
    protected void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {

        if (null != ExecuteTask)
        {

            ExecuteTask(sender, e);

        }

    }

    /// <summary>
    /// 停止事件的定时执行
    /// </summary>
    public void Stop()
    {

        if (_timer != null)
        {

            _timer.Stop();
            ExecuteTask = null;
            _timer.Dispose();
            state = false;
            _timer = null;

        }

    }
    }
}
 

2009年9月29日 | 发布:admin | 分类:技术文章 | 评论:0

发表留言: