我已经在C#.NET
. 在这方面,我使用了System.Threading.Timer
. 当我启动 10 秒间隔计时器时,执行时间之间存在一些差异。
//code
public void SetTimers(int timer, DataRow row)
{
TimeSpan dueTime;
TimeSpan interval;
SetTimeIntervals(row, out dueTime, out interval);
timer1[timer] = new System.Threading.Timer(databaseTrensfer, row, dueTime, interval);
}
public void databaseTrensfer()
{
//code
}
private void SetTimeIntervals(DataRow row, out TimeSpan tsDueTime, out TimeSpan tsPeriod)
{
string alarmType = Convert.ToString(row["EBase"]);
string EType = Convert.ToString(row["EType"]);
string EFrequency = Convert.ToString(row["EFrequncy"]);
if (alarmType == "Milisecond")
{
int frquency1 = Convert.ToInt32(row["Tfrquency"]);
tsDueTime = new TimeSpan(0, 0, 0, 0, frquency1);//frquency1=interval
tsPeriod = new TimeSpan(0, 0, 0, 0, frquency1);
}
else if (alarmType == "Second")
{
int frquency1 = Convert.ToInt32(row["Tfrquency"]);
tsDueTime = new TimeSpan(0, 0, 0, frquency1);
tsPeriod = new TimeSpan(0, 0, 0, frquency1);
}
else if (alarmType == "Once")
{
tsDueTime = new TimeSpan(0, 0, 0);
tsPeriod = new TimeSpan(0, 0, 0);
}
else if (alarmType == "Minute")
{
int frquency1 = Convert.ToInt32(row["Tfrquency"]);
tsDueTime = new TimeSpan(0, frquency1, 0);
tsPeriod = new TimeSpan(0, frquency1, 0);
}
else if (alarmType == "Hour")
{
int minute = 0;
int frquency1 = 1;
if (Convert.ToString(row["RelativeFactor"]) != "")
minute = Convert.ToInt32(row["RelativeFactor"]);
if (Convert.ToString(row["Tfrquency"]) != "")
frquency1 = Convert.ToInt32(row["Tfrquency"]);
tsDueTime = new TimeSpan(frquency1, minute, 0);
tsPeriod = new TimeSpan(frquency1, 0, 0);
}
else
{
tsDueTime = new TimeSpan();
tsPeriod = new TimeSpan();
}
}
我已经通过频率来设置定时器并同时启动定时器的数量。我的o/p:
2011-08-22 13:42:08.0
2011-08-22 13:42:18.0
2011-08-22 13:42:28.0
2011-08-22 13:42:38.15
.
.
.
2011-08-22 14:28:38.984
2011-08-22 14:28:48.984
2011-08-22 14:28:59.15
2011-08-22 14:29:09.15
2011-08-22 14:29:19.15
.
.
2011-08-22 15:14:59.953
2011-08-22 15:15:09.968
2011-08-22 15:15:19.968
我让这个 o/p 计时器在 08 秒的变化开始,然后转移到 09 秒。
现在我的问题是为什么所有计时器都没有按准确的时间执行?
有什么解决办法吗?