Reputation: 3001
I had created a windows service and i want that the service will Schedule to run daily at 6:00 Am. Below is the code which i had written:-
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
ExtractDataFromSharePoint();
}
catch (Exception ex)
{
//Displays and Logs Message
_loggerDetails.LogMessage = ex.ToString();
_writeLog.LogDetails(_loggerDetails.LogLevel_Error, _loggerDetails.LogMessage);
}
}
In the above code you can see that in OnStart
Method of service i am calling a Function ExtractDataFromSharePoint()
. How i will schedule this to run daily morning at 6:00 AM.
Upvotes: 16
Views: 73604
Reputation:
actually HERE I AM GETTING TIME INTERVAL FROM app.config file
protected override void OnStart(string[] args)
{
Timer timer = new Timer();
this._dbServiceInterval = int.Parse(ConfigurationManager.AppSettings["ServiceInterval"].ToString());
timer.Interval = (double)this._dbServiceInterval;
timer.Enabled = true;
timer.Start();
timer.Elapsed += new ElapsedEventHandler(this.timerDispatcher_Elapsed);
}
Upvotes: 0
Reputation: 3001
Thanks @Rachit for your answer and now I am able to fulfill my requirements.
static System.Timers.Timer _timer;
static string _ScheduledRunningTime ="6:00 AM";
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
_timer = new System.Timers.Timer();
_timer.Interval = TimeSpan.FromMinutes(1).TotalMilliseconds;//Every one minute
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start();
}
catch (Exception ex)
{
//Displays and Logs Message
_loggerDetails.LogMessage = ex.ToString();
_writeLog.LogDetails(_loggerDetails.LogLevel_Error, _loggerDetails.LogMessage);
}
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
//Displays and Logs Message
_loggerDetails.LogMessage = "timer_Elapsed method at :"+DateTime.Now ;
_writeLog.LogDetails(_loggerDetails.LogLevel_Info, _loggerDetails.LogMessage);
string _CurrentTime=String.Format("{0:t}", DateTime.Now);
if (_CurrentTime == _ScheduledRunningTime)
{
ExtractDataFromSharePoint();
}
}
Upvotes: 7
Reputation: 2941
Here is code that will run within a service every day at 6AM.
include:
using System.Threading;
also ensure you declare your timer within the class:
private System.Threading.Timer _timer = null;
The StartTimer function below takes in a start time and an interval period and is currently set to start at 6AM and run every 24 hours. You could easily change it to start at a different time and interval if needed.
protected override void OnStart(string[] args)
{
// Pass in the time you want to start and the interval
StartTimer(new TimeSpan(6, 0, 0), new TimeSpan(24, 0, 0));
}
protected void StartTimer(TimeSpan scheduledRunTime, TimeSpan timeBetweenEachRun) {
// Initialize timer
double current = DateTime.Now.TimeOfDay.TotalMilliseconds;
double scheduledTime = scheduledRunTime.TotalMilliseconds;
double intervalPeriod = timeBetweenEachRun.TotalMilliseconds;
// calculates the first execution of the method, either its today at the scheduled time or tomorrow (if scheduled time has already occurred today)
double firstExecution = current > scheduledTime ? intervalPeriod - (current - scheduledTime) : scheduledTime - current;
// create callback - this is the method that is called on every interval
TimerCallback callback = new TimerCallback(RunXMLService);
// create timer
_timer = new Timer(callback, null, Convert.ToInt32(firstExecution), Convert.ToInt32(intervalPeriod));
}
public void RunXMLService(object state) {
// Code that runs every interval period
}
Upvotes: 10
Reputation: 21
Here is the code that makes a call to DB and set the scheduler time based on the results :
Also, you can call a number of API calls which sends regular SMS/emails here itself.
public void ScheduleService()
{
try
{
dsData = new DataSet();
_timeSchedular = new Timer(new TimerCallback(SchedularCallBack));
dsData = objDataManipulation.GetInitialSMSConfig();
if (dsData.Tables[0].Rows.Count > 0)
{
DateTime scheduledTime = DateTime.MinValue;
scheduledTime = DateTime.Parse(dsData.Tables[0].Rows[0]["AUTOSMSTIME"].ToString());
if (string.Format("{0:dd/MM/YYYY HH:mm}", DateTime.Now) == string.Format("{0:dd/MM/YYYY HH:mm}", scheduledTime))
{
objDataManipulation.WriteToFile("Service Schedule Time Detected");
for (int iRow = 0; iRow < dsData.Tables[0].Rows.Count; iRow++)
{
if (dsData.Tables.Count > 1)
{
if (dsData.Tables[1].Rows.Count > 0)
{
sendData(dsData);
}
}
else
{
objDataManipulation.WriteToFile("No SMS Content Data !");
} }
}
if (DateTime.Now > scheduledTime)
{
scheduledTime = scheduledTime.AddDays(1);
}
TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
objDataManipulation.WriteToFile("TexRetail Service scheduled to run after: " + schedule + " {0}");
int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);
//Change the Timer's Due Time.
_timeSchedular.Change(dueTime, Timeout.Infinite);
}
}
catch (Exception ex)
{
objDataManipulation.WriteToFile("Service Error {0}" + ex.Message + ex.StackTrace + ex.Source);
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(ServiceName))
{
serviceController.Stop();
}
}
}
Upvotes: 0
Reputation: 862
Here, you have 2 ways to execute your application to run at 6 AM daily.
1) Create a console application and through windows scheduler execute on 6 AM.
2) Create a timer (System.Timers.Timer) in your windows service which executes on every defined interval and in your function, you have to check if the system time = 6 AM then execute your code
ServiceTimer = new System.Timers.Timer();
ServiceTimer.Enabled = true;
ServiceTimer.Interval = 60000 * Interval;
ServiceTimer.Elapsed += new System.Timers.ElapsedEventHandler(your function);
Note: In your function you have to write the code to execute your method on 6 AM only not every time
Upvotes: 16
Reputation: 2540
If a service is really required, look at Quartz.NET to do the scheduling for you
http://www.quartz-scheduler.net/
Upvotes: 1
Reputation: 34573
You don't need a service for this. Just create a regular console app, then use the Windows scheduler to run your program at 6am. A service is when you need your program to run all the time.
Upvotes: 10