C#定時執行,
代碼:

![]()
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common.Utils;
namespace test
{
public partial class Form1 : Form
{
/// <summary>
/// 記錄上次執行時間的文件路徑
/// </summary>
private string lastRunTimePath = Path.Combine(Application.StartupPath, "lastRunTime.txt");
/// <summary>
/// 上次執行時間,精確到秒
/// </summary>
private string lastRunTime
{
get
{
if (File.Exists(lastRunTimePath))
{
using (StreamReader sr = new StreamReader(lastRunTimePath))
{
string result = sr.ReadToEnd();
sr.Close();
return result;
}
}
return null;
}
set
{
if (!File.Exists(lastRunTimePath))
{
File.Create(lastRunTimePath);
}
using (StreamWriter sw = new StreamWriter(lastRunTimePath, false))
{
sw.Write(value);
sw.Close();
}
}
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 50; //定時執行的時間精確到秒,那麼Timer的時間間隔要小於1秒
timer.Tick += new EventHandler((a, b) =>
{
DateTime now = DateTime.Now;
if (now.ToString("yyyy-MM-dd HH:mm:ss") != lastRunTime) //如果相等則說明已經執行過了
{
lastRunTime = now.ToString("yyyy-MM-dd HH:mm:ss");
LogUtil.Log(now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 時間已到,執行任務");
//TODO:在這裡執行任務
}
});
timer.Start();
}
}
}
View Code
說明:
1、為什麼要將lastRunTime存到文件中?
這是為了程序重起的時候,仍能正確判斷時間,不會重復執行。
2、和使用Windows定時任務的方式實現有什麼區別?
這也是這種實現方式的缺點,精度不夠高,如果定時執行定時到分鐘,一般精度也只到分鐘,可以應用於對於定時時間精確程度不高的定時任務。雖然減小Interval可以提高定時精度,但耗費CPU資源。
3、為什麼要這樣實現,直接判斷時分秒不就行了嗎?
程序運行需要時間,哪怕這個時間非常短,會導致跳過某個時間,例如Interval設置為1000,也就是1秒,13時50分29.999秒執行了一次,下一次判斷的時候到了13時50分31.001秒,跳過了13時50分30秒,如果秒數用等於判斷,就不會執行了。
4、這只是個測試程序,實際使用需要根據實際情況改造一下,比如定時到分鐘就可以了,從配置文件中讀取配置的定時時間,然後按程序中的方法判斷有沒有到這個時間。
測試日志截圖:
