【问题标题】:StopWatch in C# to calculate inactivity timeC#中的秒表计算不活动时间
【发布时间】:2017-12-27 21:04:05
【问题描述】:

我有代码:

 public static Stopwatch stopWatch = new Stopwatch();

    private void start_Checker()
    {
        stopWatch.Start();
        while (true)
        {
            TimeSpan ts = stopWatch.Elapsed;
            if (ts.Minutes % 15 == 0)
            {
                Core.sendLog("Detected " + ts.Minutes + " of possible inactivity. Bot might be in game. Waiting " + (Core.inactivity_Max - ts.Minutes) + " minutes before restarting", false);
            }
            if (ts.Minutes >= Core.inactivity_Max)
            {
                Core.sendLog(Core.inactivity_Max + " minutes of inactivity - restarting the bot.");
                Thread.Sleep(500);
                Process.Start(Assembly.GetExecutingAssembly().Location);
                Environment.Exit(0);
            }
            Thread.Sleep(10000);
        }
    }

核心类中的这个:

   public static void sendLog(string text, bool isAction = true)
    {
        if (isAction)
        {
            Listener.stopWatch.Reset();
        }
        using (WebClient client = new WebClient())
        {
            try
            {
                string log = "[" + account[0] + "] " + text + " | Time: " + DateTime.Now;
                client.OpenRead(url + @"elements/logs/logs.php?file=" + used_email + "&text=" + log);
            }
            catch (Exception)
            {
                return;
            }
        }
    }

它应该每 15 分钟发送一次日志,如果 ts.Minutes 长于最大不活动时间 - 它应该重置应用程序。 每次执行sendLog(),都会重置秒表的时间。

当前代码导致日志文件中包含如下消息:

[ChristianFromDK] Detected0 of possible inactivity. Bot might be in game. Waiting 80 minutes before restarting | Time: 7/21/2017 7:50:18 PM

我做错了什么?

【问题讨论】:

  • 第一分钟分钟值为零,零模 15 为零。
  • “第一分钟” -- 以及第 15 分钟和第 30 分钟,以此类推。您的实施只是一个坏主意。如果你想每 15 分钟做一次,那就用计时器。不要轮询时钟。

标签: c# time timespan stopwatch


【解决方案1】:

由于您只是检查模数,因此每隔十秒就会有一条消息,而 StopWatch 不到一分钟,从那以后每隔 15 分钟。这是因为零模 15 为零,因此条件匹配。

如果您只想每 15 分钟调用一次,则必须将当前值与之前的值进行比较,如果超过 15 分钟,则发送消息,然后将之前的值设置为当前值。然后继续比较。

这样它只会在计时器到达 15 分钟时发生一次。还记得在秒表归零时将先前的值归零。

您也可以使用计时器在秒表归零时取消它。通常系统计时器占用的资源较少。

【讨论】:

  • 我真的很困惑。我不能只做 if( ts.Minutes != 0) 吗?为什么 ts.Minutes 的结果始终为 0,即使自上次操作以来经过的时间长于 0 分钟?
  • @PSawicki 因为Minutes 是微小的组成部分。 TotalMinutes 会给你以分钟为单位的总时间作为浮点数。但它可能永远不会完全为零、15 等,所以比较确切的数字是行不通的。
  • 我可以把它转换成 int,不是吗?
  • @PSawicki 然后它与使用Minutes 完全相同,直到您超过一小时。它不会改变任何东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 2010-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
相关资源
最近更新 更多