I wrote a program that makes use of the System.Timers.Timer name space and it is not working like expected it to.

My program listed bellow excepted two date values and determined if one date is greater than the other by using the DateTime.compare method. If one date is greater than the other, it will evaluate how much greater they are by calculating the time interval. I then convert that time interval into milliseconds and send that value to the Systems.Timer.Interval as coded bellow.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Timers;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for recorder
/// </summary>
public class recorder
{
    private string PID1;
    DateTime startDateTime;
    DateTime endDateTime;
    double interval;

	public recorder(string PID1, DateTime startDateTime, DateTime endDateTime, double Interval)
	{
        //this constructor init the data members for this class
        this.PID1 = PID1;
        this.startDateTime = startDateTime;
        this.endDateTime = endDateTime;
        this.interval = Interval;
	}

    public void startRecorder(/*string PID1, DateTime startDate, DateTime endDate*/)
    {
        //Using the class data members to calculate the dateTime diff.
        DateTime current = DateTime.Now;                                //.Parse("10/12/2007 11:12:40");
        int compareBegining = this.startDateTime.CompareTo(current);    //startDate.CompareTo(current);
        int compareEnding = this.endDateTime.CompareTo(current);        // (endDate.CompareTo(current));

        //if (BeginingInterval == 0 || BeginingInterval == -1)
        if(compareBegining == 0 || compareBegining == -1)
        {
            try
            {
                //Response.Write("The interval is: " + compareBegining.ToString());
                webServices start = new webServices();
                start.LocateServerUPL(this.PID1, this.interval);
                //start.SingleLocateMSAL(this.PID1);
                if (compareEnding == 1)
                {
                    Int32 endingTimeInSec = 0;
                    Int32 endingTimeInMilSec = 0;
                    TimeSpan b4UStop = this.endDateTime - current;
                    endingTimeInSec = Convert.ToInt32(b4UStop.TotalSeconds);
                    endingTimeInMilSec = Convert.ToInt32(b4UStop.TotalMilliseconds);

                    System.Timers.Timer time2Stop = new System.Timers.Timer();
                    time2Stop.AutoReset = false;
                    time2Stop.Enabled = true;
                    time2Stop.Interval = endingTimeInMilSec;
                    time2Stop.Elapsed += new ElapsedEventHandler(stopRecorder);
                    GC.KeepAlive(b4UStop);
                }
            }
            catch (Exception end)
            {
            }
        }
        else if (compareBegining == 1)
        {
            try
            {
                Int32 timeInSec = 0;
                Int32 timeInMilSec = 0;
                //get the time diffence between the two dates
                TimeSpan b4UStart = this.startDateTime - current;
                timeInSec = Convert.ToInt32(b4UStart.TotalSeconds);
                timeInMilSec = Convert.ToInt32(b4UStart.TotalMilliseconds);
                System.Timers.Timer time2Start = new System.Timers.Timer();
                time2Start.AutoReset = false;
                time2Start.Enabled = true;
                time2Start.Interval = timeInMilSec;
                time2Start.Elapsed += new ElapsedEventHandler(startRecorder);
                GC.KeepAlive(time2Start);

                if (compareEnding == 1)
                {
                    Int32 endingTimeInSec = 0;
                    Int32 endingTimeInMilSec = 0;
                    TimeSpan b4UStop = this.endDateTime - current;
                    endingTimeInSec = Convert.ToInt32(b4UStop.TotalSeconds);
                    endingTimeInMilSec = Convert.ToInt32(b4UStop.TotalMilliseconds);

                    System.Timers.Timer time2Stop = new System.Timers.Timer();
                    time2Stop.AutoReset = false;
                    time2Stop.Enabled = true;
                    time2Stop.Interval = endingTimeInMilSec;
                    time2Stop.Elapsed += new ElapsedEventHandler(stopRecorder);
                    GC.KeepAlive(b4UStop);
                }
            }
            catch(Exception start)
            {
            }
        }
    }

    private void startRecorder(object sender, ElapsedEventArgs e)
    {
        webServices start = new webServices();
        start.LocateServerUPL(this.PID1, this.interval);
        //Response.Write("Great job!");
    }

    private void stopRecorder(object sender, ElapsedEventArgs e)
    {
        webServices stop = new webServices();
        stop.StopRecorder(this.PID1);
        //Response.Write("2sec count");
    }
}

If the value of time2Start and time2Stop interval falls with a span of 20 minutes everything works fine. However if the two intervals fall between half hour to 45 minutes, the time2Start interval would fire as expected but the time2Stop will not execute. Additionally, if both time2Start and time2Stop falls outside of 45 minutes none of them would fire at all.

I don’t understand what is really going on at the back-end and I would like to know how I could fix this problem. This site is my last chance to get this program to work like it should or I’m going to be standing at the unemployment line.

Pleeeeeeease.

Is there anyone out there with some experience with system threads or timers? I need some help please.

hi,
do u have good articles on timers.since u have interest in timers,i want to ask u whether it is possible to send mails daily using timers,is there any possibility.

I don't have a whole lot of understanding of the subject. I've been programming for a while now and I've never had the need for timers or windows services. In this project that I am involved in, I need to write a program that will except two DateTime parameters and compare those parameters with current date and performed some work based on the calculated interval.

If you can make use of what I have so far. you are welcome to do so. However, what you see is the extent of what I know. If you find a solution elsewhere pleeeeeease let me know.

well for one justapimp, the compareto method deals with greaterthan, equal, and lessthan, not directly with integers/numbers. Try changing your == 0, 1, -1 to >0, == 0, and <0. This might solve a couple problems, whether or not they are right now or later. Also, check about just using seconds and not miliseconds. The fact is that 45 minutes in miliseconds might be a big number to compareto. Just some debugging suggestions.

Now on for a possible solution to your problem. I'll try to find one and try to understand what exactly you're doing, but fix those errors first and then we'll see what pops up.

I am using CompareTo to evaluate which of the two dates is greater. If compare to returns a -1, 0, 1 indicates that one of the date parameters is greater than, equal to or less than currentdate and my if statement would then allow me to run which ever try block that correspond to the task I want to preformed.

If StartDateTime is greater than currentDate, I calculated how much greater in term of milliseconds and used that as my delayed interval. However, if CompareTo evaluates to a -1 or 0 then I would start the task immediately.

and so I fully understand what is going on so I can help you better, why are you adding:

time2Stop.Elapsed += new ElapsedEventHandler(stopRecorder);

It seems that it takes the old variable and adds the new to it. Is this necessary? It usually doesn't hurt to have extra coding, but in a lot of cases those small extras are what causes problems.

To me, by appearance, it should work. I'll try again later

Well that is the thing. it should work for any intervals but as I mentioned before, the program will work fine so that start and stop commands are within 45 minutes. Outside of that, it will not fire any of them. I was under the impression the problem was an environment problem i.e (server settings) but its not.

as far as the code bellow, that is to add a new Event handler and in this case its a ElapsedEventHandler. without the += the compiler will complain.

time2Stop.Elapsed += new ElapsedEventHandler(stopRecorder);

What I don't understand is why would it work for interval of up to 45 minutes and not interval like an our or a day or two. After all, I am using Int32 which puts the values insides the boundaries of the max number allowed for Int32. I've recently change the data type to UInt32 to see if that was the problem and it still failed.

That is what I was thinking that it was out of bounds for the int value, but I looked into it and you are WAY under, so it shouldn't be a problem.

Your problem is most likely due to it timing out after 45 minutes. Check to see if you have a timeout somewhere on your server. It might be just too long or too many counts or something stupid. Have you tried just using seconds instead of miliseconds? It seems that timeout would be your only problem...

I tried to implement the Elapse in seconds but every article that I've read (including Microsoft MSDN pages) seems to suggest that the elapse time should be represented in milliseconds.

Even though the timer class can be instantiated, I was thinking that a newly created instance could have killed the previous instance or instances in memory. "does not make much sense".

I am so confuse about what is really going on with this program, it makes me question and consider every possible reasons why things are not working like they should.

By the way, I really appreciate all your help on this matter.

One more thing is How do I check for timer instances on the server?

Solved the problem by creating a windows service with a built in timer. Basically, I just use the original program inside a windows service and then I used my web service methods as web references inside the service.

This question has already been answered. Start a new discussion instead.