Search code examples
c#wait

Better way to constantly run function periodically in C#


I have a C# program that is constantly checking for new additions to an online DB. I have this code to have it check every 10 seconds

    static void Main(string[] args)
    {
        boolean run = true;
        while (run)
        {
            DBConnect Db = new DBConnect();

            // do amazing awesome mind blowing cool stuff

            Db.closeConnection();

            // wait for 10 seconds
            int wait = 10 * 1000;
            System.Threading.Thread.Sleep(wait);
        }
    }

i have error reporting that posts to the DB and if a major error occurs the program shuts down. Outside of the specific errors within my function, is this method secure and efficient?


Solution

  • You should rewrite your program as a windows service, that way you do not need to rely on a user to be logged for your program to run.

    If you do go with the service route, I would swap out the infinite loop for a timer.

    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
            int wait = 10 * 1000;
            timer = new Timer(wait);
            timer.Elapsed += timer_Elapsed;
    
            // We don't want the timer to start ticking again till we tell it to.
            timer.AutoReset = false;
        }
    
        private System.Timers.Timer timer;
    
        protected override void OnStart(string[] args)
        {
            timer.Start();
        }
    
        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                DBConnect Db = new DBConnect())
                try
                {
                    // do amazing awesome mind blowing cool stuff
                }
                finally
                {
                    Db.closeConnection(); //We put this in a finally block so it will still happen, even if an exception is thrown.
                }
                timer.Start();
             }
             catch(SomeNonCriticalException ex)
             {
                 MyExecptionLogger.Log(ex, Level.Waring); //Log the exception so you know what went wrong
                 timer.Start(); //Start the timer for the next loop
             }
             catch(Exception ex)
             {
                 MyExecptionLogger.Log(ex, Level.Critical); //Log the exception so you know what went wrong
                 this.Stop(); //Stop the service
             }
        }
    
        protected override void OnStop()
        {
            timer.Stop();
        }
    }