ITPub博客

首页 > 应用开发 > IT综合 > 结合Global和C#中的定时器实现自动Job(一)

结合Global和C#中的定时器实现自动Job(一)

原创 IT综合 作者:CodeAgriculture 时间:2014-01-14 21:23:52 0 删除 编辑

一、创建一个cs文件,定义Time 对象
public class WebTimer_AutoRepayment
{
    static WebTimer_AutoRepayment()
    {
        _WebTimerTask = new WebTimer_AutoRepayment();
    }

    ///


    /// 实例化
    ///

    ///
    public static WebTimer_AutoRepayment Instance()
    {
        return _WebTimerTask;
    }


    ///


    /// 实际执行的方法
    ///

    private void ExecuteMain()
    {
        //定义你自己要执行的Job
        ChinaPnrInterfaces.AutoSendRepaymentNotice();//定时发送短信提醒的方法

    }

    #region Timer 计时器定义
    ///


    /// 调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。
    ///

    private static int Period = 1 * 60 * 60 * 1000;

    ///


    /// 调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。
    ///

    private static int dueTime = 3 * 1000;//三分钟后启动

    ///


    ///第几次执行
    ///

    private long Times = 0;
    ///
    /// 实例化一个对象
    ///

    private static readonly WebTimer_AutoRepayment _WebTimerTask = null;

    private Timer WebTimerObj = null;
    ///


    /// 是否正在执行中
    ///

    private int _IsRunning;

    ///


    /// 开始
    ///

    public void Start()
    {
        if (WebTimerObj == null)
        {
            DateTime now = DateTime.Now;

            int minutes = now.Minute;
            if (minutes >= 55)
            {
                dueTime = 0;//立即启动
            }
            else
            {
                dueTime = (55 - minutes) * 60 * 1000;//到某个时间点的55分钟启动
            }

            WebTimerObj = new Timer(new TimerCallback(WebTimer_Callback), null, dueTime, Period);
        }
    }

    ///


    /// WebTimer的主函数
    ///

    ///
    private void WebTimer_Callback(object sender)
    {
        try
        {
            if (Interlocked.Exchange(ref _IsRunning, 1) == 0)
            {
                ExecuteMain();
                Times++;
                Times = (Times % 100000);
            }
        }
        catch
        {

        }
        finally
        {
            Interlocked.Exchange(ref _IsRunning, 0);
        }
    }

    ///


    /// 停止
    ///

    public void Stop()
    {
        if (WebTimerObj != null)
        {
            WebTimerObj.Dispose();
            WebTimerObj = null;
        }
    }
    #endregion
}
二、在Global文件中调用所定义的方法

 void Application_Start(object sender, EventArgs e)
    {
        //在应用程序启动时运行的代码

        WebTimer_AutoRepayment.Instance().Start(); //
    }
   
    void Application_End(object sender, EventArgs e)
    {
        //在应用程序关闭时运行的代码

        WebTimer_AutoRepayment.Instance().Stop();//
    }

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28699126/viewspace-1070601/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-03-07

  • 博文量
    54
  • 访问量
    435953