Run once a day in C#

后端 未结 10 2098
不思量自难忘°
不思量自难忘° 2020-12-09 05:00

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

相关标签:
10条回答
  • 2020-12-09 05:21

    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.

    HTH

    *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;
                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!");
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-09 05:24

    To run the job once daily between 7 and 8pm, i set up a timer with interval = 3600000 ms and then just execute the following code for timer tick.

    private void timer1_Tick(object sender, EventArgs e)
    {
        //ensure that it is running between 7-8pm daily.
        if (DateTime.Now.Hour == 19)
        { 
            RunJob(); 
        }
     }
    

    An hour window is fine for me. Extra granularity on time will require a smaller interval on the timer (60000 for a minute) and including minutes on the if.

    eg

    {
        //ensure that it is running at 7:30pm daily.
        if (DateTime.Now.Hour == 19 && DateTime.Now.Minute == 30)
        { 
            RunJob(); 
        }
     }
    
    0 讨论(0)
  • 2020-12-09 05:26

    Take a look at quartz.net. It is a scheduling library for .net.

    More specifically take a look here.

    0 讨论(0)
  • 2020-12-09 05:31

    public partial class Main : Form {
    public Main( ) // Windows Form is called Main { InitializeComponent( ); }

        private void Main_Load( object sender, EventArgs e )
        {
            /*
             This example uses a System.Windows.Forms Timer
    
             This code allows you to schedule an event at any given time in one day.
             In this example the timer will tick at 3AM.
    
             */
            Int32 alarm = GetAlarmInMilliseconds( 3, 0, 0 ); // Milliseconds until 3:00 am.
            timer_MessageCount.Interval = alarm; // Timer will tick at 3:00am.
    
            timer_MessageCount.Start( );                    
        }
    
        private Int32 GetAlarmInMilliseconds(Int32 eventHour, Int32 eventMinute, Int32 eventSecond )
        {
            DateTime now = DateTime.Now;
            DateTime eventTime = new DateTime( now.Year, now.Month, now.Day, eventHour, eventMinute, eventSecond );
    
            TimeSpan ts;
    
            if ( eventTime > now )
            {
                ts = eventTime - now;
            }
            else
            {
                eventTime = eventTime.AddDays( 1 );
                ts = eventTime - now;
            }
    
            Console.WriteLine("Next alarm in: {0}", ts );
    
            return ( Int32 ) ts.TotalMilliseconds;
        }        
    
        static void DoSomething( )
        {
            Console.WriteLine( "Run your code here." );
        }      
    
        private void timer_MessageCount_Tick( object sender, EventArgs e )
        {
            DoSomething( );
    
            Int32 alarm = GetAlarmInMilliseconds( 3, 0, 0 ); // Next alarm time = 3AM
            timer_MessageCount.Interval = alarm;            
        }
    }
    
    0 讨论(0)
提交回复
热议问题