I am having a few problems with the Timer component in ASP.NET. I can get it to work in the C# part of visual studio but not in the ASP.NET.

The thing is a number will be logged into the website so each person will need to view the same timer counting down to zero. I guess this rules out putting it in the html??

This is the code in ASP.NET. The timer1_Elapsed method is not being called though all sources tell met this is how it works.

            protected System.Timers.Timer timer1; 
            private int test; 

            protected void Page_Load(object sender, System.EventArgs e) 
            { 
                    // Put user code to initialize the page here 
                    test = 1; 

                    timer1.Interval = 1000; 
                    timer1.Start(); 

                    timer1.Enabled = true; 

            } 



            private void timer1_Elapsed(object sender,      System.Timers.ElapsedEventArgs e) 
            { 

                            test = test+1; 

                            lblCounter.Text = "count:"+test; 

            } 

In C# the 'timer1.enabled' method calls the 'timer1_Tick' which, as far as i know, is the same as the Elapsed method above.

Many thanks!!!!

Dani AI

Generated

A few things are going on here. First, System.Timers.Timer runs its Elapsed callback on a ThreadPool thread that is not part of the page life cycle, so it cannot update lblCounter in a user’s browser. Even if it fires, no postback occurs, so the label never re-renders. Also, in your snippet the timer is never instantiated or wired to an event handler, which explains why it never fires at all. In Web Forms, use either a postback (full or async) or client-side script to change what the user sees. The built-in ASP.NET AJAX Timer control is designed for this and, when paired with UpdatePanel, triggers lightweight asynchronous postbacks on an interval. (learn.microsoft.com)

For a countdown everyone sees identically, do not store a per-request counter. Persist a single server-side deadline (UTC) in durable state (database or distributed cache). Application or a static field can work on a single server, but they reset on app restart and are not shared across a farm, so treat them as volatile only. was right about needing a postback, and @f1 fan was right to push shared state; just make that state durable. (learn.microsoft.com)

Quick pattern you can drop in today:

<asp:ScriptManager runat="server" />
<asp:UpdatePanel runat="server">
  <ContentTemplate>
    <asp:Label ID="CounterLabel" runat="server" />
    <asp:Timer ID="UiTimer" runat="server" Interval="1000" OnTick="UiTimer_Tick" />
  </ContentTemplate>
</asp:UpdatePanel>
protected void UiTimer_Tick(object s, EventArgs e)
{
    // Persist once elsewhere: Application["DeadlineUtc"] or DB
    var deadline = (DateTime)Application["DeadlineUtc"];
    var remaining = deadline - DateTime.UtcNow;
    CounterLabel.Text = remaining > TimeSpan.Zero ? remaining.ToString(@"hh\:mm\:ss") : "00:00:00";
}

Notes: 1-second polling from many users adds load; prefer a client-side countdown seeded with the server deadline and occasionally resync via AJAX. If you truly need server-push (no polling) so everyone flips to zero at the same instant, broadcast updates with SignalR. (learn.microsoft.com)

Recommended Answers

All 8 Replies

i might be wrong but i dont think you can use a timer in asp.net because inorder to change a value on the page it has to do a postback, which reloads the page each time.

but ive seen this done with ajax. like using
setTimeout() to loop and XMLHttpRequest to do the postback

magicajax.net makes it easy

the timer is doing its function i bet. But test is reset on each postback so will always be 1. for everyone to have the same function you should put test in the application cache (or store is somewhere outside of the session - maybe a db or file).

Hello my friend!

The timer control does not work with asp.net because web application is stateless. In order to simulate a timer in asp.net you need to use javascript.

I created a control that I call it KYNOUAJAXContainer that basically can be used as a timer. For example, if you want a clock on the top of the page, all you have to do is drop a Label control into this KYNOUAJAXContainer control and in the page load event set the current time to the label's text property.

I posted some tutorials at the same website where I uploaded the KYNOUAJAXContainer control. Go ahead and check it out! Logon to

I hope I helped :)

Hi!
I created a control that I named KYNOUAJAXContainer that can be found at . This control allows you to add regular ASP.NET controls into it and they all become AJAX enabled. You can use this container control as a sort of timer control for ASP.NET. This is because the container control has a property called ShouldRefresh. When this property is set to true, it will refresh the content of all the controls inside of the container every RefreshInterval seconds (RefreshInterval is another property of the container control).
I posted tutorials that will walk you through the steps to use the control at under the Tutorial Index => Ajax => KYNOU AJAX Controls link

Timer controls work well on an asp.net page. As a web page refreshes each time it is back, You should declare the time control as a static attribute of the page, as well as the timer event handler.
Hope this help.

Timer controls work well on an asp.net page. As a web page refreshes each time it is back, You should declare the time control as a static attribute of the page, as well as the timer event handler.
Hope this help.

I have done as it is as you provided..........downloaded kynoucontrols,added to the ttol box and then in page load I added the code to display time........but it not running..........any idea

The timer can be used in ASP.NET page as follows:

protected System.Timers.Timer _timer;
protected void Page_Init(object sender, EventArgs e)
{
        // initialize the time control
        _timer = new System.Timers.Timer(5000);

        // subscribe to the Elapsed event
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
}

protected void Page_Load(object sender, EventArgs e)
{
            _timer.Start();
}

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
            // Do whatever you want to do on each tick of the timer
}

Try the Timer1_Tick event.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.