C# Execute function at specific time

后端 未结 6 944
暖寄归人
暖寄归人 2020-12-06 03:06

I made a little Windows Forms program to do some auto backup of some files on my disk. Right now I need to push a button before it is executed, but I want to make the progra

相关标签:
6条回答
  • 2020-12-06 03:46

    sorry for posting a answer after so many year. i feel my post may help some one later. here is a small code to simulate schedule task with timer.

    using System;
    using System.Timers;
    
    namespace ScheduleTimer
    {
        class Program
        {
            static Timer timer;
    
            static void Main(string[] args)
            {
                schedule_Timer();
                Console.ReadLine();
            }
    
            static void schedule_Timer()
            {
                Console.WriteLine("### Timer Started ###");
    
                DateTime nowTime = DateTime.Now;
                DateTime scheduledTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 8, 42, 0, 0); //Specify your scheduled time HH,MM,SS [8am and 42 minutes]
                if (nowTime > scheduledTime)
                {
                    scheduledTime = scheduledTime.AddDays(1);
                }
    
                double tickTime = (double)(scheduledTime - DateTime.Now).TotalMilliseconds;
                timer = new Timer(tickTime);
                timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
                timer.Start();
            }
    
            static void timer_Elapsed(object sender, ElapsedEventArgs e)
            {
                Console.WriteLine("### Timer Stopped ### \n");
                timer.Stop();
                Console.WriteLine("### Scheduled Task Started ### \n\n");
                Console.WriteLine("Hello World!!! - Performing scheduled task\n");
                Console.WriteLine("### Task Finished ### \n\n");
                schedule_Timer();
            }
        }
    }
    

    screen shot

    0 讨论(0)
  • 2020-12-06 03:48

    You can use the task scheduler in Windows to set programs to run at a specific time. Check out this link. It refers to the built-in Windows backup but there's no reason you can't have it run your own program instead.

    Actually, this link to the AT command might be better.

    I know you were looking for a programming solution (and several others have posted on how to use timers) but the advantage of scheduling something with the AT command is that your program does not need to remain running on the system all of the time. The task scheduler will start your program at the right time, it can execute and then it exits. You might need to tweak your program a little to have it backup automatically and then exit but that should be possible.

    0 讨论(0)
  • 2020-12-06 03:52

    You can use: System.Forms.Timer

    If you don't know the amount of time until you want to Execute do something like:

    DateTime TimeToExecuteTask
    DateTime Now = DateTime.Now // assign values.
    
    int SecondsToExectution = (TimeSpan)(TimeToExecuteTask - Now).TotalSeconds;
    
    0 讨论(0)
  • 2020-12-06 03:56

    One option is to use a timer. This requires that your program keep running.

    If you want to use a timer then set it to fire (every second, for example)

    myTimer.Interval = 1000;
    

    In the delegate function that's called, compare the current time with your target time and if they match, launch your backup process.

    0 讨论(0)
  • 2020-12-06 03:57

    Not a 100% dupe, but you'll find this SO question interesting. ;)

    Contains references to quartzTimer and other options.

    0 讨论(0)
  • 2020-12-06 04:02
        //Perhaps the following is a more suitable solution consume the following
    
        public class DailyTrigger
        {  
            readonly TimeSpan triggerHour;
    
            public DailyTrigger(int hour, int minute = 0, int second = 0)
            {
              triggerHour = new TimeSpan(hour, minute, second);
              InitiateAsync();
            }
    
            async void InitiateAsync()
            {
              while (true)
              {
                var triggerTime = DateTime.Today + triggerHour - DateTime.Now;
                if (triggerTime < TimeSpan.Zero)
                  triggerTime = triggerTime.Add(new TimeSpan(24, 0, 0));
                await Task.Delay(triggerTime);
                OnTimeTriggered?.Invoke();
              }
            }
    
            public event Action OnTimeTriggered;
          }
    
    
       // as Follows
    
         var trigger = new DailyTrigger(17); // every day at 5:00pm
    
              trigger.OnTimeTriggered += () =>
              {
                //Do Logic
              };
    
    0 讨论(0)
提交回复
热议问题