解决定时执行代码可能跳过的问题

一般我们在开发项目时,可能会有些功能需要用线程去定时去处理,比如短信定时发送、数据定时统计等等。但既然是定时,一定就是一个时间点。那么程序就有可能在这个时间点上,并没有运行到你所写的代码上来,或是错过了。这样就可以达不到我们的目的。下面是我解决此方法的相关代码。

//创建一个线程
System.Threading.Thread tread03 = new System.Threading.Thread(new System.Threading.ThreadStart(Threads03));
//启动线程
tread03.Start();

void Threads03()
{
    
//每天12:00执行一次
    DateTime temp_dt = default(DateTime);
    
while (true)
    {
        DateTime exec_dt 
= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"+ " 12:00:00");
        DateTime new_dt 
= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:00"));
        
if (DateTime.Compare(new_dt.AddMinutes(-3), exec_dt) < 0 && DateTime.Compare(new_dt.AddMinutes(3), exec_dt) > 0)
        {
            
if (DateTime.Compare(exec_dt, temp_dt) != 0)
            {
                
//在为里写相关功能处理代码
                temp_dt = exec_dt;
            }
        }
        System.Threading.Thread.Sleep(
60000);  //休眠一分钟
    }
}
原文地址:https://www.cnblogs.com/linyechengwei/p/1597809.html