本文介绍了每 x 分钟运行一段代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..我正在尝试编写一个程序,它每 x 分钟执行一次操作.我一直在试验秒表功能,但它似乎没有在时间到时运行我想要的代码.
I'm trying to make a program whereby it does something every x minutes. I have been experimenting with the Stopwatch function but it don't seem to run the code I want when the time is up.
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
namespace Testing
{
class Program
{
static void Main(string[] args)
{
Stopwatch testing = new Stopwatch();
testing.Start();
Thread.Sleep(6001);
TimeSpan ts = testing.Elapsed;
int timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
Console.Write(timer);
while (testing.Elapsed < TimeSpan.FromMinutes(8))
{
timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
if (timer % 60 == 0)
{
//run x code every 1 minutes
Console.WriteLine("1 min" + timer);
}
timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
if (timer % 120 == 0)
{
//run x code every 2 minutes
Console.WriteLine("2 min" + timer);
}
}
testing.Stop();
}
}
}
推荐答案
根据 xxbbcc 的建议,这里是使用 ManualResetEvent.WaitOne() 和 TimeOut 的实现:
As suggested by xxbbcc, here's an implementation using ManualResetEvent.WaitOne() with a TimeOut:
static void Main(string[] args)
{
int TimeOut = (int)TimeSpan.FromMinutes(2).TotalMilliseconds;
System.Threading.ManualResetEvent mreDuration = new System.Threading.ManualResetEvent(false);
Task.Run(() => {
System.Threading.Thread.Sleep((int)TimeSpan.FromMinutes(30).TotalMilliseconds);
mreDuration.Set();
});
while(!mreDuration.WaitOne(TimeOut))
{
Console.WriteLine("Two Minutes...");
}
Console.WriteLine("Thirty Mintues!");
Console.ReadLine();
}
这篇关于每 x 分钟运行一段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论