.NET,每分钟事件(每分钟).计时器是最好的选择吗? [英] .NET, event every minute (on the minute). Is a timer the best option?

查看:31
本文介绍了.NET,每分钟事件(每分钟).计时器是最好的选择吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在使用 c# 的 Windows 窗体应用程序中每分钟(按时钟)做一些事情.我只是想知道最好的方法是什么?

I want to do stuff every minute on the minute (by the clock) in a windows forms app using c#. I'm just wondering whats the best way to go about it ?

我可以使用计时器并将其间隔设置为 60000,但要让它在每分钟运行,我必须精确地在每分钟启用它,这不太可行.

I could use a timer and set its interval to 60000, but to get it to run on the minute, I would have to enable it on the minute precisely, not really viable.

我可以使用计时器并将其间隔设置为 1000.然后在其滴答事件中,我可以根据我设置的变量检查时钟当前分钟,如果分钟已更改,则运行我的代码.这让我很担心,因为我让我的电脑每 1 秒检查一次,以便每 1 分钟执行一次工作.这肯定很丑吗?

I could use a timer and set its interval to 1000. Then within its tick event, I could check the clocks current minute against a variable that I set, if the minute has changed then run my code. This worries me because I am making my computer do a check every 1 second in order to carry out work every 1 minutes. Surely this is ugly ?

我使用的是 windows 窗体和 .Net 2.0,所以不想使用 .Net 3.5 附带的 DispatchTimer

I'm using windows forms and .Net 2.0 so do not want to use the DispatchTimer that comes with .Net 3.5

这一定是一个相当普遍的问题.你们有没有更好的方法来做到这一点?

This must be a fairly common problem. Have any of you a better way to do this?

推荐答案

以阿奎那的答案为基础,该答案可以漂移,并且不会在一分钟的一秒内准确地打勾:

Building on the answer from aquinas which can drift and which doesn't tick exactly on the minute just within one second of the minute:

static System.Timers.Timer t;

static void Main(string[] args)
{
    t = new System.Timers.Timer();
    t.AutoReset = false;
    t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
    t.Interval = GetInterval();
    t.Start();
    Console.ReadLine();
}

static double GetInterval()
{
    DateTime now = DateTime.Now;
    return ((60 - now.Second) * 1000 - now.Millisecond);
}

static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    Console.WriteLine(DateTime.Now.ToString("o"));
    t.Interval = GetInterval();
    t.Start();
}

在我的盒子上,这段代码在每分钟的 0.02 秒内持续滴答:

On my box this code ticks consistently within .02s of each minute:

2010-01-15T16:42:00.0040001-05:00
2010-01-15T16:43:00.0014318-05:00
2010-01-15T16:44:00.0128643-05:00
2010-01-15T16:45:00.0132961-05:00

这篇关于.NET,每分钟事件(每分钟).计时器是最好的选择吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆