D.N.E.Z
D.N.E.Z

Reputation: 63

how to set the timer interval for one day in a windows service

I have created a windows service.In which I have set the timer interval for every one minute and so it was triggering for every minute,. But I need to trigger the same for each day..

You can find the code below where I have set the timer interval in OnStart() method..

Code:

    protected override void OnStart(string[] args)
    {
        TraceService("start service");

        //handle Elapsed event
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

        //This statement is used to set interval to 1 minute (= 60,000 milliseconds)

        timer.Interval = 86400000;

        //enabling the timer
        timer.Enabled = true;
    }

Upvotes: 1

Views: 10477

Answers (3)

Mobeen Rashid
Mobeen Rashid

Reputation: 1

In C# now you can use TimeSpan class to get total milliseconds in day to set a per day timer.

var totalMilliSecondsPerDay = TimeSpan.FromDays(1).TotalMilliseconds;
var timer = new Timer(totalMilliSecondsPerDay);

Upvotes: 0

Aref Karimi
Aref Karimi

Reputation: 1880

This post is quite old but I think it's worth mentioning that instead of using a magic number like 86400000 it's better to use something like new TimeSpan(1, 0, 0, 0).TotalMilliseconds , so that if someone needs to change it they will know what should be changed.

Upvotes: 5

So, couple of things regarding your post:

First, it does not state what is the problem!

Technically, Timer supports a timer interval of about 25 days. So, your code should work.

If you want to exceed 25 days and you are not concerned about thread safety, I suggest you go to System.Threading.Timer.

More info here

Since, your service runs as a windows based service, i suggest you go to System.Threading.Timer.

Upvotes: 0

Related Questions