.NET,每分钟事件(每分钟).计时器是最好的选择吗?

编程入门 行业动态 更新时间:2024-10-25 08:17:36
本文介绍了.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,每分钟事件(每分钟).计时器是最好的选择吗?

本文发布于:2023-06-07 15:25:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:每分钟   计时器   事件   是最好的   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!