-->

Better way to constantly run function periodically

2020-07-30 06:43发布

问题:

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?

回答1:

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();
    }
}


回答2:

Write it as a console program without the wait and set up a scheduled task to run it periodically. You want to run it every 10 seconds? Every minute? Just change the scheduled task.

You can use the Task Scheduler GUI, or the schtasks command line tool.

See Programs are not cats.



回答3:

I would setup a windows service and use SqlDependency http://msdn.microsoft.com/en-CA/library/a52dhwx7(v=vs.80).aspx. That way when a change (which you specify) occurs in the database, it will trigger the OnChange event which you specify to do whatever it is you need to do. See the link for implementation details.



标签: c# wait