Avatar of Deraldo Silva
Deraldo Silva
 asked on

sophisticated timer control in asp.net

Hi.
I have an asp.net application running normally at lan. Sometimes there is internet connection and sometimes dont. Because of this, I receive some files to import or from internet or manually placed into a local folder.

to handle this, I created an httpmodule. after a interval time (configured) if there is a local file, I process it and check if there is connection. If there is, I check if there is some file to download. If there is, I do that and store it in the same folder. After the next interval, the process continues.

so. everything is working fine, except the timer. all the timers that I use do not stop the counter. even when stopped, the events are queued.
The best timer was the System.Diagnostics.StopWatch. however, how handle the interval? thread.sleep() no please.

thx for any help
C#ASP.NET

Avatar of undefined
Last Comment
Deraldo Silva

8/22/2022 - Mon
Ammar Gaffar

Why you are implementing this functionality in ASP.NET?

The purpose of this functionality is to sync with specific folder, I do recommend to implement it as a Windows Service using FileSystemWatcher to monitor any added files to your configured folder and execute the rest of your code, in this case you don't even need the timer because FileSystemWatcher has Created event.

Good Luck
Deraldo Silva

ASKER
Hi Ammar.
Thx for your attention.

well. I have two reasons.
1. is not only to synchronize with a folder. If the internet connection is present, then I can get the records from it. I only realized that if I download the records as file from the internet site, I have only one process to manage.
2. the sites could be remote, hard to manage. an asp.net application has a simple instalation .

regards
kaufmed

StopWatch isn't a timer; rather it's a chronograph. Timers count down to some interval; chronographs count up until stopped.

We would probably need to see your module code to fully understand what you are doing.
Your help has saved me hundreds of hours of internet surfing.
fblack61
Miguel Oz

Please answer questions below:
Q1. What kind of timers have you used?
Q2. What do you mean by "all the timers that I use do not stop the counter"?
Q3. Have you used Threading.Timer or Timers.Timer
Q4. is the execution of your timer callback > timer interval? If so, you may need to synchronize or disable the timer until execution is done as discussed here.
Deraldo Silva

ASKER
Ok.
as attached some pictures about the problem.
I will try to disable the timer, using the duetime in system.threading. Am I right?
timerSnapshot.docx
kaufmed

I suppose that while the process is stopped at line 123, the timer count still goes on.
It shouldn't be--you set the timer's AutoReset to false. Is the File.Exists code in the timer_Elapsed handler? Are you sure you're not calling that same method elsewhere?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Deraldo Silva

ASKER
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DataTable dt;
            byte[] b1 = null;

            // check if there is a xlsx file in "diretorio"
 
            string arquivo = diretorio + "\\BBBMatUnidadesDeNegocio.xlsx";
            if (File.Exists(arquivo))
            {
                dt = new DAL().Get_ExcelSheet(arquivo);
                foreach (DataRow dr in dt.Rows)
                {
                    using (var nucleo = new Nucleo())
                    {
                        var bo = new UnidadeDeNegociosBo(nucleo);
                        UnidadesDeNegocio unidade = new UnidadesDeNegocio();
                        unidade.UnidadeDeNegocioID = dr["CODIGO"].ToString();
                        unidade.Descricao = dr["DESCRICAO"].ToString();
                        try
                        {
                            bo.IncluirUnidadeDeNegocio(unidade);
                        }
                        catch (AggregateException ex)
                        {
                            nucleo.Undo();
                        }
                    }
                }
                File.Delete(arquivo);
            }
            b1 = receiveFile("BBBMatUnidadesDeNegocio.xlsx");
            if (b1 != null)
            {
                // get the file from web service
                FileStream fs1 = new FileStream(arquivo, FileMode.Create);
                fs1.Write(b1, 0, b1.Length);
                fs1.Close();
                fs1 = null;
            }
            timer.Start();
        }
kaufmed

Why do you have timer.Start as the last line of the event handler? That's why your timer fires more than once.
Deraldo Silva

ASKER
Hi.
I took off the timer.Start on the last line and the problem still the same.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Miguel Oz

I think you have a re-entrant problem in your elapsed method (your timer is firing the elapsed method again because the interval < elapsed execution time); to solve it, you need to disable timer, run your code and then enable timer again as shown below: (A try finally for final production code is recommended)
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
  timer.Enable = false; // or timer. Stop();
  //your code goes here
  timer.Enable = true; //timer.Start();
}

The only issue is that the timer will no longer fires at exactly the specified configuration interval but the new elapsed time = specified configuration interval  + elapsed execution time.
If your problem is only debugging (as described in doco) then you need code above only for debugging purposes unless you may face big execution times in production.
Deraldo Silva

ASKER
Sorry Miguel.
this did not work either. still the same problem.
the interval not have to be regular. In production will be for example, each hour.
Deraldo Silva

ASKER
Hey. it works fine if I run it without debug.
only with debug it duplicate the records.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Miguel Oz

How are you declaring timer variable?
It should be declared private static and instantiated in a singleton pattern as shown here.
Deraldo Silva

ASKER
I put the static. Did not work eiher.
I already used the lock condition. did not work.
you think I need to try this again?
thx in advance.
ASKER CERTIFIED SOLUTION
Miguel Oz

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Deraldo Silva

ASKER
Hi Miguel.
Send me your email and I send the code to you.

Well. Now I am thinking in other solution than httpmodule. Before all this oddities(as you said) , the httpmodule looks a great solution.

But if the debug problem is relative to timer, will be good know the solution isnt?

regards
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Deraldo Silva

ASKER
I change the project to windows service and everything is working fine.
thx for your help.