我正在制作一个程序,每30或60分钟必须检查一次数据库,并在Windows窗体界面中显示结果(如果有的话)。当然,在执行数据库检查时,from提供访问的其他功能仍然可用。为此,我使用的是System.Timers.Timer,它在与UI不同的线程上执行一个方法(如果使用这种方法有问题,请随时评论它)。我写了一个小而简单的程序,以测试热门的工作,只是注意到我不能真正设置Interval超过1分钟(我需要30分钟到一个小时)。我提出了这个解决方案:
public partial class Form1 : Form
{
int s = 2;
int counter = 1; //minutes counter
System.Timers.Timer t;
public Form1()
{
InitializeComponent();
t = new System.Timers.Timer();
t.Elapsed += timerElapsed;
t.Interval = 60000;
t.Start();
listBox1.Items.Add(DateTime.Now.ToString());
}
//doing stuff on a worker thread
public void timerElapsed(object sender, EventArgs e)
{
//check of 30 minutes have passed
if (counter < 30)
{
//increment counter and leave method
counter++;
return;
}
else
{
//do the stuff
s++;
string result = s + " " + DateTime.Now.ToString() + Thread.CurrentThread.ManagedThreadId.ToString();
//pass the result to the form`s listbox
Action action = () => listBox2.Items.Add(result);
this.Invoke(action);
//reset minutes counter
counter = 0;
}
}
//do other stuff to check if threadid`s are different
//and if the threads work simultaneously
private void button1_Click(object sender, EventArgs e)
{
for (int v = 0; v <= 100; v++)
{
string name = v + " " + Thread.CurrentThread.ManagedThreadId.ToString() +
" " + DateTime.Now.ToString(); ;
listBox1.Items.Add(name);
Thread.Sleep(1000); //so the whole operation should take around 100 seconds
}
}
}
但是这样,Elapsed事件被提升并且timerElapsed方法每分钟调用一次,看起来有点无用。有没有办法实际设置更长的计时器间隔?
答案 0 :(得分:5)
间隔以毫秒为单位,因此您似乎将间隔设置为60秒:
t.Interval = 60000; // 60 * 1000 (1 minute)
如果您希望间隔1小时,则需要将间隔更改为:
t.Interval = 3600000; // 60 * 60 * 1000 (1 hour)