c#定時器和global實現自動job示例

轉:https://www.jb51.net/article/46328.htm 

 public class WebTimer_AutoRepayment
{
    static WebTimer_AutoRepayment()
    {
        _WebTimerTask = new WebTimer_AutoRepayment();
    }
    /// <summary>
    /// 實例化
    /// </summary>
    /// <returns></returns>
    public static WebTimer_AutoRepayment Instance()
    {
        return _WebTimerTask;
    }
    /// <summary>
    /// 實際執行的方法
    /// </summary>
    private void ExecuteMain()
    {
        //定義你自己要執行的Job
        ChinaPnrInterfaces.AutoSendRepaymentNotice();//定時發送短信提醒的方法
    }
    #region Timer 計時器定義
    /// <summary>
    /// 調用 callback 的時間間隔(以毫秒爲單位)。指定 Timeout.Infinite 可以禁用定期終止。
    /// </summary>
    private static int Period = 1 * 60 * 60 * 1000;
    /// <summary>
    /// 調用 callback 之前延遲的時間量(以毫秒爲單位)。指定 Timeout.Infinite 以防止計時器開始計時。指定零 (0) 以立即啓動計時器。
    /// </summary>
    private static int dueTime = 3 * 1000;//三分鐘後啓動
    /// <summary>
    ///第幾次執行
    /// </summary>
    private long Times = 0;
    /// <summary>
    /// 實例化一個對象
    /// </summary>
    private static readonly WebTimer_AutoRepayment _WebTimerTask = null;
    private Timer WebTimerObj = null;
    /// <summary>
    /// 是否正在執行中
    /// </summary>
    private int _IsRunning;
    /// <summary>
    /// 開始
    /// </summary>
    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);
        }
    }
    /// <summary>
    /// WebTimer的主函數
    /// </summary>
    /// <param name="sender"></param>
    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);
        }
    }
    /// <summary>
    /// 停止
    /// </summary>
    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();//
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章