Click here to Skip to main content
Click here to Skip to main content

Web Timer Control

By , 7 Oct 2008
 
page.png
Figure: Timer GUI

Introduction

Timer control is purely a Web-based control.

Timer Class

  • Provides a mechanism for executing a method at specified intervals.
  • Timer control's stopwatch counts downwards from 'X' to ZERO time for measuring elapsed time.

Events

OnIntervalReached

Notifies your application when a specified period of time has elapsed. It is triggered through a client callback method. So you can't update the page contents from this event.

protected void Timer1_IntervalReached(object sender, CodeControls.TimerEventArgs e)
{

}

OnTimeOutOccurred

Notifies your application when a specified Time Out has been reached.

protected void Timer1_TimeOutOccurred(object sender, CodeControls.TimerEventArgs e)
{

}

property.png

Figure: Properties and Events

Implementation

Timer control is built on Client CallBack technique. So no postback is required for notifying your application when interval or timeout is reached.

Since the mechanism implements client callback method, you are limited to the following:

  • You can perform database operations.
  • You can't redirect the current page
  • You can't modify the content of the current page.
  • You can have access to the cookies and cache.
  • You can't store the value in the session. This is because posted session values are available after the post back.

To overcome this limitation, this control provides a mechanism to do a full post back on Time Out.

So you can modify, redirect the current page if DoPostBackOnTimeOut attribute is set to TRUE.

Properties & Definition

IsAutoStart

If set to true, Timer countdown starts immediately after page load.

If set it to false, Timer countdown won't be triggered at the page load. You should call Timer1.ManualStart() method in your page to trigger the Timer.

Enabled

If it is set to false, it won't register the related script to the page.

To run Timer, this property needs to be set to true.

ServerSideTimeSynchronize

The Timer control runs based on a JavaScript. We can't claim that Timer control always maintains perfect timings. It might miss a couple of seconds.

If ServerSideTimeSynchronize is set to true, the time calculations are based on the server. After each interval, the timer gets the amount of Time left from the server and updates the stop watch.

This is will lead to slight bumps in the countdown.

DoPostBackOnTimeOut

Timer StopWatch is a JavaScript based program. When the interval is reached, it enables the client callback functions.

So no post back is required for notifying your application when interval or timeout is reached. As a result of this ClientCallBack, you can't modify the page contents.

This property allows control to trigger a TimeOut event with full post back. Now, you can modify the contents or redirect to another page.

This won't create a postback for the IntervalReached event.

DisableRightClick

It disables the mouse right click. Mouse right click affects the timer stopwatch. So it is recommended to set DisableRightClick to true.

If you don't want to disable the mouse right click, then set ServerSideTimeSynchronize to true.

This is done so that it updates the Timer StopWatch for every interval.

Interval

Interval is defined in seconds.

Raises an IntervalReached event on your application when a specified period of time has elapsed.

TimeOut

TimeOut is defined in seconds.

Raises a TimeOut event on your application when a TimeOut has elapsed.

It is raised only once for entire Timer period.

***Timer is set to last interval time, when a postback occurs.

Creating a New Timer Control

Add the following to your *.aspx page.

<%@ Register Namespace="CodeControls" TagPrefix="cc" %>

<cc:Timer ID="Timer1" runat="server" DoPostBackOnTimeOut="false" Font-Names="Verdana"
    Font-Size="68px" ForeColor="#FF8000" Interval="5" ServerSideTimeSynchronize="True"
    TimeOut="9" OnIntervalReached="Timer1_IntervalReached"
    OnTimeOutOccurred="Timer1_TimeOutOccurred" IsAutoStart="true"
    DisableRightClick="true"></cc:Timer>

Using a Timer Control

Suppose you want to update the date time on the server for every 10 seconds.

You could create a Timer to periodically update date time on the SQL server.

Specifying Time on a Timer Control

See Interval and Timeout properties. Both are defined in seconds.

Specifying Themes on a Timer Control

Timer control inherits Label properties. So you can use it like ASP.NET Label.

Specifying Stop Watch Visibility on a Timer Control

If you don't want to display the stopwatch/countdown, you can set visibility to false. But Timer controls runs regardless of visible property. Only Enable property disables the Timer control.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

Prem Rajadattan

United States United States

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionissue when using the controlmemberthe algabban29-May-12 15:56 
hi i face this issue when i use timer control " Parser Error Message: Unknown server tag 'cc:Timer' " can you help me PLZ
Knowledge, even if they are small it's right for everyone

QuestionHow to pause the timermemberhina_best22222@yahoo.co.in1-Apr-12 20:33 
Hi, how can we pause the timer for some time.
QuestionServer Errormembermamta20121-Mar-12 18:37 
When I used this control I got error as below:
Parser
Error Message: Unknown server tag 'cc:Timer'.
 
Source Error:
 

Line 154:                                <br />
Line 155:                            Time Remaining:
Line 156:<cc:Timer ID="Timer1" runat="server" Font-Bold="True" Font-Names="Verdana" Font-Size="11px" Interval="10" IsAutoStart="true"
Line 157:                                DisableRightClick="False" DoPostBackOnTimeOut="true" ServerSideTimeSynchronize="True"
Line 158:                                OnIntervalReached="Timer1_IntervalReached" OnTimeOutOccurred="Timer1_TimeOutOccurred"></cc:Timer>
 
It's working fine on local server but giving error on production server.
AnswerRe: Server Errormemberhina_best22222@yahoo.co.in1-Apr-12 20:34 
Add <%@ Register Namespace="CodeControls" TagPrefix="cc" %> in the page you are using timer control
GeneralRe: Server Errormemberthe algabban29-May-12 15:57 
I did added but still not working , not even in the local server
Knowledge, even if they are small it's right for everyone

Generaladd repeatable properties !memberikuto tohoin25-Jan-11 17:01 
i think it will be more usefull if timer can repeat counting.
i only know code to show up repeatable in properties
 
private bool _repeatable;
        [Description("repeat after Timeout.")]
        [Category("Timer Settings")]
        public bool Repeatable
        {
            get
            {
                return _repeatable;
            }
 
            set
            {
                _repeatable = value;
            }
        }
 
but i don't know where add code to repeat counting...
GeneralTimermemberclaudiajs27-May-10 22:30 
Thanks, i risolve doing this:
I have to modify
 
#region Call Back Timer Public Declaration
@"
//Define a custom object 'Timer'
Timer = new Object();
Timer.Interval={0};
Timer.TimeOut={1};
Timer.TimeLeft={1};
Timer.SynchronizeStopWatch={2};
Timer.CountDown=
{{
AsyncBlush | :O ,
Sync:1
}};
Timer.RefCallBackTimer;
Timer.RefCountDownTimer;
Timer.Display;
Timer.MilliSecond=0;
Timer.Second=0;
Timer.Minute=0;
Timer.Hour=0;
Timer.Days=0;
Timer.IsPostBackOnTimeOut='{3}';
";
#endregion
 
Timer.UpdateCountDownTimer=function ()
{
Timer.Days=Math.floor(Timer.TimeLeft/86400);
Timer.Hour=Math.floor((Timer.TimeLeft-Timer.Days*86400)/3600);
Timer.Minute = Math.floor((Timer.TimeLeft-Timer.Days*86400-(Timer.Hour*3600)) / 60);
Timer.Second = Timer.TimeLeft -Timer.Minute * 60 - Timer.Hour*3600 -Timer.Days*86400;
Timer.MilliSecond=0;
 
}
 
//and this part of the class
 

Timer.Display=document.getElementById('__DControls__Timer__Display');
Timer.Display.innerHTML =Timer.Days+ ':' + Timer.Hour+':'+ Timer.Minute+':'+Timer.Second+'.'+Timer.MilliSecond;
if(Timer.TimeLeft>0)
Timer.RefCountDownTimer=setTimeout('Timer.ShowCountDownTimer()',100);
else
{
if(Timer.IsPostBackOnTimeOut=='true')
Timer.CallTimeOutHandler();
}
 
if you have a best solution, thanks
 
Ciaoo
GeneralAdd Daysmemberclaudiajs24-May-10 23:07 
Hi, your control is excellent, but i have a answer, is possible add the days to the control.???
 
Thanks
 
Claudia
GeneralRe: Add DaysmemberPrem Rajadattan25-May-10 12:04 
I think you can add days to the Timer. You may need to add something like
 
Javascript
-------------------
Timer.Days=Math.floor(Timer.TimeLeft/3600*24);
if(Timer.Days>0)
Timer.Display.innerHTML =Timer.Days+' days :'+Timer.Hour+':'+ Timer.Minute+':'+Timer.Second+'.'+Timer.MilliSecond;
else
Timer.Display.innerHTML =Timer.Hour+':'+ Timer.Minute+':'+Timer.Second+'.'+Timer.MilliSecond;
QuestionHow to keep track of the start and stop timer duration?memberavishekrc17-Mar-10 5:59 
Hi,
I just want to have a timer control in C sharp Web based Application. I want to keep track of the time between two button clicks.So one button click event will start the timer and the other will stop and I need that time duration.
How can I do the same using your custom control?
What should I write inside your :
Thanks in advance.
Avi
GeneralThats GreatmemberAMK_SDK30-Sep-09 21:43 
Thank you for this useful control, but i have a little problem.
i am using the timer for creating a quiz countdown. and i use timeout event to handle the calculation of score and redirect to another page to show the result. after redirecting successfully to result page, i receive the "Response.Redirect cannot be called in a Page callback." exception on the Page.Response.Redirect("Result.aspx"); line of code. my timer control properties status is as follow (as you mentioned in article):
 
DoPostBackOnTimeOut = True
ServerSideTimeSynchronize = False

know that this is quit strange but i need urgent help.
 
thank you
GeneralGood articlememberDonsw27-Jan-09 7:27 
Nice read
GeneralUrgent Help NeededmemberMember 421903222-Apr-09 17:56 
Hi there,
I am badly in need of timer control. After searching thru, I found out that this can be used with few modifications.
First of all thanks to the author, for providing this source code.
I am a very newbie.. When I try to add this code, it gives below error
 
Element 'Timer' is not a known element. This can occur if there is a compilation error in the Web site.
 
The type or namespace name 'CodeControls' could not be found (are you missing a using directive or an assembly reference?)
 
There is no APP_Code folder in my project.
So what should I do? Where should I place timer1.Cs file?/
 
Urgent help needed.
 
Thanks very much in advance
Regards
GeneralNice control, but i have a questionmemberewanko21827-Oct-08 1:57 
i'm doing an online exam application... is there a way in which the timer won't restart, when a user submits an answer? The timer should continue until the user is finished with the exam... THANKS!
GeneralIts Interestingmembershiva.jayaraman20-Oct-08 23:52 
hi,
      This is sivakumar,I got your source code its working fine but when i create a post back timer again running from starting value. what i need is when create a post timer won't restart. please can i get a code for that.
 
Thanks in advance....
     
Email ID:shiva.jayaraman@yahoo.co.in,
GeneralRe: Its Interestingmemberauthord21-Oct-08 19:27 
If a postback occurs ,the timer will be set to the last interval time...
For example
Timer countdown goes like this 10:00:00..9:59:59....9:59:01....9:58:12...
Timer interval occurs at 9:50:00...
PostBack occurs at 9:43:00, the Timer loaded again ,now timer continue from the last interval time 9:50:00
 
...You can also try by setting SyncWithServerSide to true...but this will create a slight bumps in the Stopwatch...
...Or every 5sec you can read/update the Timer cookie through javascript
 
please let me know if you need anything....
Generalseems interestingmembersaber_solomon6-Oct-08 22:08 
seems interesting but where is source code?
 

GeneralRe: seems interestingmemberauthord7-Oct-08 7:23 
i have added the source code....
GeneralRe: seems interestingmembersaber_solomon7-Oct-08 20:55 
thanks Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130617.1 | Last Updated 7 Oct 2008
Article Copyright 2008 by Prem Rajadattan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid