?
Solved

set timer in windows service

Posted on 2010-11-11
14
Medium Priority
?
816 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
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 
LVL 42

Accepted Solution

by:
sedgwick earned 2000 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 2000 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 2000 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 2000 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 2000 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

Application Discovery Service in AWS

In the era of the cloud, customers migrating away from their existing on-premise infrastructure. This requires lots of planning, strategies, and effort to identify their existing resources and determine how best to migrate.  Datacenter migrations happen in four phases -

Question has a verified solution.

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

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
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
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

752 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