Run once a day in C#

后端 未结 10 2096
不思量自难忘°
不思量自难忘° 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: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;            
        }
    }
    

提交回复
热议问题