我有代码:
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.分钟比最大不活动时间长 - 它应该重置应用程序。 每次执行sendLog()
时,它都会重置秒表的时间。
当前代码导致日志文件收到如下消息的垃圾邮件:
[ChristianFromDK] Detected0 of possible inactivity. Bot might be in game. Waiting 80 minutes before restarting | Time: 7/21/2017 7:50:18 PM
我做错了什么?
由于您只是检查模数,因此每十秒就会有一条消息,而StopWatch
不到一分钟,从那里开始每 15 分钟一次。这是由于零模 15 为零,因此条件匹配。
如果您只想每 15 分钟调用一次,则必须将当前值与以前的值进行比较,如果超过 15 分钟,请发送消息,然后将以前的值设置为当前值。然后继续比较。
这样,当计时器达到 15 分钟时,它只会发生一次。还要记住在秒表归零时将以前的值归零。
您还可以使用计时器在秒表归零时取消它。通常,系统计时器的资源密集度较低。