Reputation: 9416
System.Timers.Timer scheduleTimer = new System.Timers.Timer();
DateTime dtPrevDate = new DateTime();
public Service1()
{
InitializeComponent();
scheduleTimer.Enabled = true;
int timerInterval = //number of seconds to the next 7th day of either current or next month;
scheduleTimer.Interval = timerInterval
scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
}
protected override void OnStart(string[] args)
{
this.scheduleTimer.Start();
dtPrevDate = DateTime.Now.Date;
Logger.CreateLog("Service started");
}
In the sample code above in my Windows service, how can i get the number of seconds to the next 7th day of either current or next month irrespective of whether the service was stopped, restarted or the server was rebooted?.
Upvotes: 0
Views: 241
Reputation: 14133
You can use this utility function to get the DateTime
that corresponds to the next n
th day of either this or the following month.
private DateTime GetNthDay(int n)
{
DateTime today = DateTime.Today;
DateTime nthDay = new DateTime(today.Year, today.Month, n);
if ( nthDay <= today )
{
nthDay = nthDay.AddMonths(1);
}
return nthDay;
}
Using that, the rest is just basic math.
DateTime dtPrevDate = DateTime.Now;
DateTime dtNextDate = GetNthDay(7);
Double secondsTo7thDay = (dtNextDate - dtPrevDate).TotalSeconds;
Upvotes: 1