Run once a day in C#

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

    You could query time and run if your within some time frame, that way even if the machine goes off you'll call the method or use a timer like Vinko's suggestion.

    But the better solution (akin to older CRON versions, so its a proven pattern) is to have some persistent data, with the cheapest solution I can think of right now being a blank file, check its last modified attribute, and if it hasn't been modified within the last 24 hours you touch it and run your method. This way you assure the method gets run first thing in the case the application is out for the weekend for example.

    I've done this in C# before, but its was a year ago at another Job, so I don't have the code but it was about 20 lines (with comments and all) or so.

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

    There may be problems if the computer reboots so you could run the application as a windows service.

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

    If you only want to run it once a day and don't care when, this will work (will run just after midnight).

    Declare a DateTime variable:

    DateTime _DateLastRun;
    

    In your startup, set the initial date value:

    _DateLastRun = DateTime.Now.Date;
    

    In the logic area where you want to check whether to perform the action:

    if (_DateLastRun < DateTime.Now.Date) 
    {
        // Perform your action
        _DateLastRun= DateTime.Now.Date;
    }
    
    0 讨论(0)
  • 2020-12-09 05:13

    You can try this solution.

        public Main()
        {
            StartService();
        }
    
        public async Task StartService(CancellationToken token = default(CancellationToken))
        {
            while (!token.IsCancellationRequested)
            {
                ExecuteFunction();
                try
                {
                    await Task.Delay(TimeSpan.FromDays(1), token);
                }
                catch (TaskCanceledException)
                {
                    break;
                }
            }
        }
    
        public async Task ExecuteFunction()
        {
            ...
        }
    
    0 讨论(0)
  • 2020-12-09 05:17

    Here is how you can do it if you're running a Windows Forms Application. But you need to configure a setting so that you can store the last date the event was fired. If you never intend to close the app you can just store the date as a static value.

    Im using a timer to fire the event, as following:

            private void tmrAutoBAK_Tick(object sender, EventArgs e)
            {
                if (BakDB.Properties.Settings.Default.lastFireDate != DateTime.Now.ToString("yyyy-MM-dd"))
                {
                     tmrAutoBAK.Stop(); //STOPS THE TIMER IN CASE OF EVENTUAL MESSAGEBOXES.
                     createBakup(); //EVENT
                     BakDB.Properties.Settings.Default.lastFireDate = DateTime.Now.ToString("yyyy-MM-dd"); //STORING CURRENT DATE TO SETTINGS FILE.
                     BakDB.Properties.Settings.Default.Save(); //SAVING THE SETTING FILE.
                     tmrAutoBAK.Start(); //RESTARTING TIMER
                }
            }
    
    0 讨论(0)
  • 2020-12-09 05:18

    If the time when it is run is not relevant and can be reset each time the program starts you can just set a timer, which is the easiest thing to do. If that's not acceptable it starts getting more complex, like the solution presented here and which still doesn't solve the persistence problem, you need to tackle that separately if you truly wish to do what Scheduled Tasks would. I'd really consider again if it's worth going through all the trouble to replicate a perfectly good existing functionality.

    Here's a related question (Example taken from there).

    using System;
    using System.Timers;
    
    public class Timer1
    {
        private static Timer aTimer = new System.Timers.Timer(24*60*60*1000);
    
        public static void Main()
        {
            aTimer.Elapsed += new ElapsedEventHandler(ExecuteEveryDayMethod);
            aTimer.Enabled = true;
    
            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine();
        }
    
        // Specify what you want to happen when the Elapsed event is 
        // raised.
        private static void ExecuteEveryDayMethod(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        }
    }
    
    0 讨论(0)
提交回复
热议问题