有什么聪明的方法可以让我的 executeEveryDayMethod() 每天执行一次,而不必涉及 Windows TaskScheduler?
最佳答案
我通过执行以下操作实现了这一点......
- 设置一个每 20 分钟触发一次的计时器(尽管实际时间由您决定 - 我需要在一天中多次运行)。
- 在每个 Tick 事件中,检查系统时间。将时间与您的方法的计划运行时间进行比较。
- 如果当前时间小于计划时间,请检查某个持久存储中的 a 以获取该方法上次运行的日期时间值。
- 如果该方法上次运行时间超过 24 小时,则运行该方法,并将本次运行的日期时间存储回您的数据存储
- 如果该方法最后一次运行是在过去 24 小时内,请忽略它。
HTH
*编辑 - C# 中的代码示例::注意:未经测试...
using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Timer t1 = new Timer();
t1.Interval = (1000 * 60 * 20); // 20 minutes...
t1.Elapsed += new ElapsedEventHandler(t1_Elapsed);
t1.AutoReset = true;
t1.Start();
Console.ReadLine();
}
static void t1_Elapsed(object sender, ElapsedEventArgs e)
{
DateTime scheduledRun = DateTime.Today.AddHours(3); // runs today at 3am.
System.IO.FileInfo lastTime = new System.IO.FileInfo(@"C:\lastRunTime.txt");
DateTime lastRan = lastTime.LastWriteTime;
if (DateTime.Now > scheduledRun)
{
TimeSpan sinceLastRun = DateTime.Now - lastRan;
if (sinceLastRun.Hours > 23)
{
doStuff();
// Don't forget to update the file modification date here!!!
}
}
}
static void doStuff()
{
Console.WriteLine("Running the method!");
}
}
}
关于c# - 在 C# 中每天运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/280566/