每天跑一次

And*_*s R 16 c# scheduling

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

问候

/安德斯

Zom*_*eep 17

我通过以下方式实现了这一目标......

  1. 设置一个每20分钟触发一次的计时器(虽然实际时间由你决定 - 我需要在一天中多次运行).
  2. 在每个Tick事件中,检查系统时间.将时间与方法的计划运行时间进行比较.
  3. 如果当前时间小于计划时间,请检查某个持久存储中的某个以获取上次运行该方法的日期时间值.
  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!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


res*_*efm 8

看看quartz.net.它是.net的调度库.

更具体地来看看这里.

  • "经过两年多的开发,错误修复和新功能Quartz.NET终于成熟到版本1.0." 我知道调度比第一眼看上去困难得多.两年,克隆! (2认同)