我正在尝试制作一个程序,它每x分钟执行一次。我一直在尝试使用秒表功能,但它似乎并没有运行我想要的代码,当时间到了。每x分钟运行一次代码
这里是我的代码:
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,因为它似乎适合我想要做的更多,但是我只能设法使代码运行一次使用计时器,我所寻找的是每x分钟,该代码将运行一次。 例如,我将程序运行时间设置为30分钟。在30分钟的运行时间内,我希望程序每隔2分钟重复Console.WriteLine(“2分钟已到”),直到30分钟结束。请帮我:) – Konny
@Konny我用'System.Timers.Timer'用一些代码更新了我的答案。 – xxbbcc