c#准時器和global完成主動job示例。本站提示廣大學習愛好者:(c#准時器和global完成主動job示例)文章只能為提供參考,不一定能成為您想要的結果。以下是c#准時器和global完成主動job示例正文
1、創立一個cs文件,界說Time 對象
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
}
2、在Global文件中挪用所界說的辦法
void Application_Start(object sender, EventArgs e)
{
//在運用法式啟動時運轉的代碼
WebTimer_AutoRepayment.Instance().Start(); //
}
void Application_End(object sender, EventArgs e)
{
//在運用法式封閉時運轉的代碼
WebTimer_AutoRepayment.Instance().Stop();//
}