System.Timers.Timer(定时器)

https://www.cnblogs.com/i-cheng/p/10018801.html

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;
}
}
}

posted @   yinghualeihenmei  阅读(419)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示