c# - 在 C# 中每天运行一次

标签 c# scheduling

有什么聪明的方法可以让我的 executeEveryDayMethod() 每天执行一次,而不必涉及 Windows TaskScheduler?

最佳答案

我通过执行以下操作实现了这一点......

  1. 设置一个每 20 分钟触发一次的计时器(尽管实际时间由您决定 - 我需要在一天中多次运行)。
  2. 在每个 Tick 事件中,检查系统时间。将时间与您的方法的计划运行时间进行比较。
  3. 如果当前时间小于计划时间,请检查某个持久存储中的 a 以获取该方法上次运行的日期时间值。
  4. 如果该方法上次运行时间超过 24 小时,则运行该方法,并将本次运行的日期时间存储回您的数据存储
  5. 如果该方法最后一次运行是在过去 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/

相关文章:

linux - 如何知道 schedule() 调用何时因信号返回?

linux - Linux 中的任务调度程序行为

c# - C#中主线程和其他线程的基准测试

c# - 使用联合安全保护服务器应用程序之间的 WCF 服务调用

c# - 使用命令行禁用 FIPS

linux - 使用 perf 确定进程何时以及为何进入不间断 sleep

c# - 实现哈希的最佳实践?

c# - 关闭主窗体隐藏的 winforms 应用程序

hadoop - 如何依次依次运行MapReduce作业

node.js - 寻找一个在作业仍在运行时不会启动的 Node.js 调度程序