We help IT Professionals succeed at work.

How to create a timer

RockBaby
RockBaby asked
on
306 Views
Last Modified: 2008-01-09
Hi,

I'm new to c#. i would like to create a timer running background on my console application. then every hour (compare to UTC time) it will auto update a SQL table. any idea how to create?

Regards,
RockBaby
Comment
Watch Question

CERTIFIED EXPERT

Commented:
using System;
using System.Data;

namespace CONS
{
      /// <summary>
      /// Summary description for Class1.
      /// </summary>
      class Class1
      {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            ///

            public static System.Windows.Forms.Timer FTimer;
            [STAThread]
            static void Main(string[] args)
            {
                  FTimer = new System.Timers.Timer();
                  FTimer.Interval = 1000;//set interval in milliseconds;
                  FTimer.Start();
                  FTimer.Tick += new EventHandler(FTimer_Tick);
            }

            private static void FTimer_Tick(object sender, EventArgs e)
            {
                  // do what u want here this function will be called after ur interval period till u stop the timer
            }
      }
}
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
That won't work.  When the last line of Main() is hit..your app will simply exit!  (it doesn't matter that you have a timer running)

You could either poll in an infinite loop and check the time or derive a class from the ApplicationContext class:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwindowsformsapplicationcontextclasstopic.asp
CERTIFIED EXPERT

Commented:
i know that i just wanted to show what he needs to do create a timer

he may have other processes to do after creatting the timer

if not he can create an infinte loop after the timer creation :-)
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
man.. this is confusing..
somemore got showing false example..

Author

Commented:
ok.. i manage to get the timer works..
but let's say i open up my application at 8.45am...
the console application will be running backend... but i wan it start the timer ar 9am..
or i open up my application at 3.10pm.. and the timer will start updating at 4pm
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
Grab the current time and add 1 to the hour field.  Then make a new DateTime instance using that hour.  Next subtract the current time from that time to get a TimeSpan instance.  Now you can set your first Timer interval to the TotalMilliseconds value of that TimeSpan.  When the Timer fires the first time, change the Interval to an Hour.

Author

Commented:
erm. i dun really understand..
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsApplication1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new myContext());
        }
    }

    public class myContext : ApplicationContext
    {

        private DateTime dt;
        private System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer();

        public myContext()
        {                      
            if (DateTime.Now.Hour < 23)
            {
                dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour + 1, 0, 0);
            }
            else
            {
                dt = DateTime.Today.AddDays(1);
                dt = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0);
            }
            TimeSpan ts = dt.Subtract(DateTime.Now);            

            tmr.Interval = Convert.ToInt32(ts.TotalMilliseconds);
            tmr.Tick += new EventHandler(tmr_Tick);
            tmr.Start();
        }

        void tmr_Tick(object sender, EventArgs e)
        {

            // do something in here...

            // make it fire again at the next hour...
            dt = dt.AddHours(1);
            TimeSpan ts = dt.Subtract(DateTime.Now);
            tmr.Interval = Convert.ToInt32(ts.TotalMilliseconds);
        }

    }

}

Author

Commented:
i'm building a console application. the system does not read forms..
for the statement below how to change to console apps?

private System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer();

Author

Commented:
erm.. no need.. i found it...

Author

Commented:
how to fix this?

public class myContext : ApplicationContext

The type or namespace name 'ApplicationContext' could not be found (are you missing a using directive or an assembly reference?)
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
It is part of System.Windows.Forms.

Author

Commented:
the problem is i'm creating a Console Application.. whenever i put System.Windows.Forms, it will show this error :

The type or namespace name 'Windows' does not exist in the class or namespace 'System' (are you missing an assembly reference?)
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
High School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
i'm using Visual Studio 2003 and how to right click reference and add reference?
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
For the 2003 versions, I only have VB.Net 2003.   (I have Vb.Net 2005 Express and C# 2005 Express as well...)

In the "Solution Explorer" pane (where your forms/classes for your project are listed) there should be a "References" entry.

Right click that "References" entry and select "Add Reference".  Then find and click on the "System.Windows.Forms.dll" entry.  Finally click on the "Select" button.

Author

Commented:
ok. i have added "System.Windows.Forms.dll" entry but couldn't find System.Collections.Generic;
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
You won't as that is specific to C# 2005.  It is not necessary for the code I supplied (it is added by default by the IDE).

Author

Commented:
i got it work..
i dun think tat is correct.. because my system need to update every hour.. every 10am, 11am, 12pm,....

from the app tat u have coded is like it choose the nearest 10am.. if i close and open my app again.. the system will update the same data rite?

can i compare the time.. like let's say if the minute and second equal to 0, then my app will update?
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
What the code does is adjusts the Timer Interval so that you will get an event at the top of the next hour.

When that event fires you do whatever YOU want.

Then after that, at the bottom of the Tick() event, the code AGAIN adjusts the Timer Interval so that it will fire again at the top of the NEXT hour.

It will repeat this forever until you close it.

I don't understand what you mean by this:

    "the system will update the same data rite?"

I'm not updating anything...as that is up to you to code.  

The Timer only fires at the top of the hour.  If you open it at 9:31 am and close it 5 mins later then no event will have fired.  If you open it again at 9:52 am then it will still fire the first event at 10:00 am.

Author

Commented:
i manage to get my own logic works. thanks anyway

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.