Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

set timer in windows service

Posted on 2010-11-11
14
803 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
ID: 34111586
the method is part of the windows service?
is the windows service meant to run manually or auto?
0
 

Author Comment

by:ToString1
ID: 34111631
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
ID: 34111685
the method can be run stabdalone from a scheduler which uses the data from its app.config
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 42

Accepted Solution

by:
sedgwick earned 500 total points
ID: 34111793
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
ID: 34111807
your app.config should have TimeInterval in appSettings:
</configuration>
  <appSettings>
    <add key="TimeInterval" value="500" />
  </appSettings>
</configuration>
0
 

Author Comment

by:ToString1
ID: 34111884
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
ID: 34112079
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
 

Author Comment

by:ToString1
ID: 34112118
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
ID: 34112149
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
ID: 34112165
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
ID: 34112267
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
ID: 34112273
>>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
ID: 34112332
OK what about daily
0
 
LVL 42

Expert Comment

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

Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

789 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