Solved

set timer in windows service

Posted on 2010-11-11
14
796 Views
Last Modified: 2012-05-10
I'm building a c#  windows service I would like some code to call a method periodically say every, hour or every 24 hours (which can be amended from app.config)

I would like code snippet for this and be able to get config values from app.config
0
Comment
Question by:ToString1
  • 9
  • 5
14 Comments
 
LVL 42

Expert Comment

by:sedgwick
Comment Utility
the method is part of the windows service?
is the windows service meant to run manually or auto?
0
 

Author Comment

by:ToString1
Comment Utility
I am calling the a method that is outside of the windows service and already have a reference to that.    The windows service would start automatically I think but am unsure.

Also writing to an event log would be good.
0
 
LVL 42

Expert Comment

by:sedgwick
Comment Utility
the method can be run stabdalone from a scheduler which uses the data from its app.config
0
 
LVL 42

Accepted Solution

by:
sedgwick earned 500 total points
Comment Utility
create a C# timer and set its interval to whatever you want.
the OnTimer event will be calling this method:

//windows service code
protected override void OnStart(string[] args)
        {
CreateTimer();
            base.OnStart(args);
        }

private void CreateTimer()
{
//read app.config values such as interval time
int timeInterval = int.Parse(ConfigurationManager.AppSettings["TimeInterval"]);

//create timer
timer1.Interval = timeInterval;
timer1.Enabled = true;
timer1.Tick += new System.EventHandler (OnTimerEvent);
}

private static void OnTimerEvent(object source, EventArgs e)
{
//add the code to call your method
}
0
 
LVL 42

Assisted Solution

by:sedgwick
sedgwick earned 500 total points
Comment Utility
your app.config should have TimeInterval in appSettings:
</configuration>
  <appSettings>
    <add key="TimeInterval" value="500" />
  </appSettings>
</configuration>
0
 

Author Comment

by:ToString1
Comment Utility
ok thanks

So in my windows service project (visual studio) I have a file called program.cs

        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
                  {
                        new TestService()
                  };
            ServiceBase.Run(ServicesToRun);
        }


I want to leave this file alone and just use TestService  so where would I put the code
0
 
LVL 42

Assisted Solution

by:sedgwick
sedgwick earned 500 total points
Comment Utility
so you need to create a class called TestService.
add reference to System.Windows.Forms for Timer class.
override OnStart() and insert the following code:
 protected override void OnStart(string[] args)
        {
CreateTimer();
            base.OnStart(args);
        }

private void CreateTimer()
{
//read app.config values such as interval time
int timeInterval = int.Parse(ConfigurationManager.AppSettings["TimeInterval"]);

//create timer
timer1.Interval = timeInterval;
timer1.Enabled = true;
timer1.Tick += new System.EventHandler (OnTimerEvent);
}

private static void OnTimerEvent(object source, EventArgs e)
{
//add the code to call your method
}
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:ToString1
Comment Utility
OK thanks but I am instantiating

System.Timers.Timer

but I don't get the tick property, I would like to use the Elapsed  property
0
 
LVL 42

Assisted Solution

by:sedgwick
sedgwick earned 500 total points
Comment Utility
instead of timer1.Tick += new System.EventHandler (OnTimerEvent):

use this:
 timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);

and add the following event handler:
 static void timer1_Elapsed(object sender, ElapsedEventArgs e)
        {
            //call your method
        }
0
 

Author Comment

by:ToString1
Comment Utility
Brilliant thanks very much

One last thing in app.config, say I want to set intervals for 1 hour, 2 hour ,3 hour upto daily

Thanks!
0
 
LVL 42

Assisted Solution

by:sedgwick
sedgwick earned 500 total points
Comment Utility
the interval which Timer uses is in millisecond.
so simply convert the configuration value to milisecond.
the best way is to use TimeSpan expression:

</configuration>
  <appSettings>
    <add key="TimeInterval" value="1.02:03:04.1" />
  </appSettings>
</configuration>

//code
string timeInterval = int.Parse(ConfigurationManager.AppSettings["TimeInterval"]);
timer1.Interval = TimeSpan.Parse(timeInterval).TotalMilliseconds;

the timespan expression is parse like this:

d.hh:mm:ss.ms

d-days
hh-hours
mm-minutes
ss-seconds
ms-milliseconds

so the following expression "12.09:45:22.87" means:
12 day, 9 hours, 45 minutes, 22 seconds and 87 millisecond
0
 
LVL 42

Expert Comment

by:sedgwick
Comment Utility
>>One last thing in app.config, say I want to set intervals for 1 hour, 2 hour ,3 hour upto daily

is you mean every 1 hour then:
</configuration>
  <appSettings>
    <add key="TimeInterval" value="01:00:00" />
  </appSettings>
</configuration>
0
 

Author Comment

by:ToString1
Comment Utility
OK what about daily
0
 
LVL 42

Expert Comment

by:sedgwick
Comment Utility
daily is every 24 hrs so:
</configuration>
  <appSettings>
    <add key="TimeInterval" value="24.00:00:00" />
  </appSettings>
</configuration>
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now