Solved

set timer in windows service

Posted on 2010-11-11
14
807 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
[X]
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
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
MYSQL responding very slow 3 50
asp.net uploading picture to a temporary folder 4 26
C# XML Get Values 4 35
C# Windows Form Navigation - Total Beginner 9 48
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
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.
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

733 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