Solved

set timer in windows service

Posted on 2010-11-11
14
802 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
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…

777 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