我创建了一个Windows服务,我希望该服务将安排在每天早上6点运行。 以下是我写的代码: -
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);
}
}
在上面的代码中,您可以看到OnStart
服务方法我正在调用函数ExtractDataFromSharePoint()
。我将如何安排在每天早上6点开始运行。
答案 0 :(得分:13)
在这里,您有两种方法可以执行您的应用程序,以便每天早上6点运行。
1)创建一个控制台应用程序,并通过Windows调度程序在上午6点执行。
2)在Windows服务中创建一个定时器(System.Timers.Timer),它在每个定义的时间间隔内执行,在你的函数中,你必须检查系统时间是否= 6 AM然后执行你的代码
ServiceTimer = new System.Timers.Timer();
ServiceTimer.Enabled = true;
ServiceTimer.Interval = 60000 * Interval;
ServiceTimer.Elapsed += new System.Timers.ElapsedEventHandler(your function);
注意:在您的函数中,您必须编写代码才能在每个上午6点执行您的方法
答案 1 :(得分:6)
您不需要为此服务。只需创建一个常规控制台应用程序,然后使用Windows计划程序在早上6点运行您的程序。服务就是您需要程序一直运行的时间。
答案 2 :(得分:6)
以下是每天早上6点在服务中运行的代码。
包括:
using System.Threading;
还要确保在班级中声明您的计时器:
private System.Threading.Timer _timer = null;
下面的StartTimer函数包含开始时间和间隔时间,目前设置为从早上6点开始并每24小时运行一次。如果需要,您可以轻松地将其更改为在不同的时间和间隔开始。
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
}
答案 3 :(得分:5)
感谢@Rachit的回答,现在我能够满足我的要求。
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();
}
}
答案 4 :(得分:1)
如果确实需要服务,请查看Quartz.NET以便为您安排
答案 5 :(得分:0)
以下是调用DB并根据结果设置调度程序时间的代码:
此外,您可以拨打多个API调用,这些调用会在此处发送常规短信/电子邮件。
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();
}
}
}