手机
当前位置:查字典教程网 >编程开发 >C#教程 >c#定时器和global实现自动job示例
c#定时器和global实现自动job示例
摘要:一、创建一个cs文件,定义Time对象复制代码代码如下:publicclassWebTimer_AutoRepayment{staticWe...

一、创建一个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

}

二、在Global文件中调用所定义的方法

复制代码 代码如下:

void Application_Start(object sender, EventArgs e)

{

//在应用程序启动时运行的代码

WebTimer_AutoRepayment.Instance().Start(); //

}

void Application_End(object sender, EventArgs e)

{

//在应用程序关闭时运行的代码

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

}

【c#定时器和global实现自动job示例】相关文章:

C# 对XML操作入门实例

c#实现无标题栏窗口的拖动

C#编写的windows计算器的实例代码

c# 类和成员的修饰详细介绍

c#初学简单程序实例代码介绍

c#文件的复制,移动,创建(实例代码)

C# 汉字转拼音(全拼和首字母)实例

c#自定义泛型类的实现

C# 注册表 操作实现代码

c#一个定时重启的小程序实现代码第1/2页

精品推荐
分类导航