C# – Run once a day in C#


Is there any clever method out there to make my executeEveryDayMethod() execute once a day, without having to involve the Windows TaskScheduler?

Best Solution

I achieved this by doing the following...

  1. Set up a timer that fires every 20 minutes (although the actual timing is up to you - I needed to run on several occasions throughout the day).
  2. on each Tick event, check the system time. Compare the time to the scheduled run time for your method.
  3. If the current time is less than the scheduled time, check a in some persistent storage to get the datetime value of the last time the method ran.
  4. If the method last ran more than 24 hours ago, run the method, and stash the datetime of this run back to your data store
  5. If the method last ran within the last 24 hours, ignore it.


*edit - code sample in C# :: Note : untested...

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;


        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)
                    // Don't forget to update the file modification date here!!!

        static void doStuff()
            Console.WriteLine("Running the method!");