准确的三分钟时间间隔时间 [英] Accurate three-minute time timer intervals

查看:149
本文介绍了准确的三分钟时间间隔时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的上一个问题中,我询问了四舍五入的时间值到最近的第三个-分钟。
现在我有一些问题,我的System.Threading.Timer必须工作,当第三分钟的时间到了。我执行以下操作:

In my previos question I asked about rounding time value to nearest third-minute. Well now I have some issues with my System.Threading.Timer that must work when is third-minute time is come. I Do following:

private System.Timers.Timer WorkTimer;
//...
public void StartProccessing()
{
WorkTimer = new System.Timers.Timer();
WorkTimer.AutoReset = false;
WorkTimer.Elapsed += new ElapsedEventHandler(WorkTimer_Elapsed);
StartWorkTimer();
}
//...
private void StartWorkTimer()
        {
            WorkTimer.Interval = (CurrentTime.AddMinutes(3) - DateTime.Now).TotalMilliseconds;
            WorkTimer.Start();
        }
void WorkTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            WorkTimer.Stop();
            this.ProcessData(this.CurrentTime);
            StartWorkTimer();
        }

问题是定时器启动时 - 在第三分钟的时间内不工作,它在第三分钟后开始工作。例如:
定时器在15.02.2012 12:20:32.871启动,在15.02.2012 12:21:00.000中必须工作WorkTimer_Elapsed,但是从15.02.2012开始:12:24:01.871。 如何解决这个问题?
我修复了我的CurrentTime时间(从前一个问题):

Problem is that the when timer started - it is not work in first third-minute time, its begin working after second third-minute time. For example: Timer is started at 15.02.2012 12:20:32.871, in 15.02.2012 12:21:00.000 it must work WorkTimer_Elapsed, but its begin from 15.02.2012 12:24:01.871. How to fix this? I fix my CurrentTime time (from previos question):

private DateTime CurrentTime
        {
            get
            {
                DateTime now = DateTime.Now.AddSeconds(30);
                DateTime val;
                val = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0)
                     .AddMinutes(((now.Minute) / 3) * 3 - now.Minute);
                return val;
            }
        }


推荐答案

这里的问题是你到最近的第3分钟,但是为了让你的计时器工作,你必须使用最近的一个。

The problem here is that you round to the nearest 3rd minute, but for your timer to work you have to use the most recent one.

所以,如果你删除 AddSeconds(30),您的计时器应按预期工作。

So, if you remove the AddSeconds(30), your timer should work as expected.

在旁注:您的舍入算法应该添加90秒(因为这是3分钟的一半)而不是30.如果你在12:31:50加30秒,你最终会有12:30:00,而应该是12:33:00。

On a side note: your rounding algorithm should add 90 seconds (as that's the half of 3 minutes) rather than 30. If you're adding 30 seconds to 12:31:50, you'd end up with 12:30:00, but it should be 12:33:00 instead.

这篇关于准确的三分钟时间间隔时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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