System.Timers.Timer(定时器)

1.System.Timers命名空间下的Timer类。System.Timers.Timer类:定义一个System.Timers.Timer对象,然后绑定Elapsed事件,通过Start()方法来启动计时,通过Stop()方法或者Enable=false停止计时。AutoReset属性设置是否重复计时(设置为false只执行一次,设置为true可以多次执行)。Elapsed事件绑定相当于另开了一个线程,也就是说在Elapsed绑定的事件里不能访问其它线程里的控件(需要定义委托,通过Invoke调用委托访问其它线程里面的控件)。

System.Timers.Timer MTM_Timer;

//定义作业执行时间
private readonly double MTM_Interval = Convert.ToDouble(ConfigurationManager.AppSettings["MTMShareCountryMain"]);
private static int RunFlag = 0;

//定义固定时间执行
private readonly int EXECMTMShareCountry = Convert.ToInt32(ConfigurationManager.AppSettings["EXECMTMShareCountry"]);

public void MTMShareCountryMain()
{

RunFlag = 0;

if (MTM_Timer == null)
{
RunFlag = 0;
MTM_Timer = new System.Timers.Timer();

//周期时间
MTM_Timer.Interval = MTM_Interval;

//到达时间的时候执行事件
MTM_Timer.Elapsed += new System.Timers.ElapsedEventHandler(MTMShareCountry);

//是否执行Elapsed事件
MTM_Timer.Enabled = true;

//设置是执行一次(false)还是一直执行(true)
MTM_Timer.AutoReset = true;

//启动作业
MTM_Timer.Start();
}

}
private void MTMShareCountry(object sender, System.Timers.ElapsedEventArgs e)
{
if (DateTime.Now.Hour == EXECMTMShareCountry)//判断当前时间与定义时间是否一致
{
if (RunFlag == 1)
return;
RunFlag = 1;


try
{
InitializeShareCountry();//调用后台方法
}
catch (Exception ex)
{

}
finally
{
RunFlag = 0;
}

}
}

原文地址:https://www.cnblogs.com/i-cheng/p/10018801.html