Timed events overlapping during execution
<p>I am having an issue with the a Service I used to perform automated tasks.
The service uses a Timer and executes after 20 seconds. </p>

<p>The function that is executed opens the database, reads from it, sends the values through the network, receives a response and updates the database with that response. </p>

<p>Its been working well until I wanted to carry out the automated tasks for about 1000 rows in the database and the system 'failed'. After checking my logs, I found out that the function executes after the interval even while a previous instance is still executing. The function is supposed to send a message and some clients complained of not getting a message while others got as much as six time.</p>

<p>Is there any simple and efficient way to make sure the function will not run if a previous instance is still running.</p>

<p>If I start and stop the time in the function, it will only add the "passed" time to the interval</p>

<p>Here is the code</p>

<pre><code>public partial class Service1 : ServiceBase
{
    private Timer timer1 = null;

    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        timer1 = new Timer();
        this.timer1.Interval = 20000;
        this.timer1.Elapsed += new  System.Timers.ElapsedEventHandler(this.timer1_Tick);
        timer1.Enabled = true;
        Library.WriteErrorLog("service has started");
    }

    private void timer1_Tick(object sender, ElapsedEventArgs e)
    {
        try
        {
        //retrieve data from database
        //read rows

        //Loop through rows
        //send values through network
        //receive response and update db
        }
        catch (Exception ex)
        {
            Library.WriteErrorLog(ex);
        }
    }
}

    protected override void OnStop()
    {
        timer1.Enabled = false;
        Library.WriteErrorLog("service has stopped");
    }
}
</code></pre>