我有一个用SQL Server 2008 R2编写的存储过程,需要每天运行。存储过程接受两个日期start date
& end date
并根据这些日期从table A
获取数据并将其写入table B
。
为了自动执行每天运行存储过程的任务,我编写了一个Windows服务。我已在Service1.cs
安排了我的任务,如下所示:
System.Timers.Timer oTimer = null;
public ServiceExample()
{
InitializeComponent();
oTimer = new System.Timers.Timer();
SetTimer();
}
private void SetTimer()
{
DateTime currentTime = DateTime.Now;
int intervalToElapse = 0;
DateTime scheduleTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 8, 0, 0); //run at 8 am every morning
if (currentTime <= scheduleTime)
intervalToElapse = (int)scheduleTime.Subtract(currentTime).TotalSeconds;
else
intervalToElapse = (int)scheduleTime.AddDays(1).Subtract(currentTime).TotalSeconds;
oTimer = new System.Timers.Timer(intervalToElapse);
oTimer.Elapsed += new System.Timers.ElapsedEventHandler(oTimer_Elapsed);
oTimer.Start();
}
void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//make connection to SQL and call the SP
DBLibrary oDBLibrary = new DBLibrary();
DataSet dsCustomer = oDBLibrary.getCustomerDetails();
oTimer.Interval = (24 * 60 * 60 * 1000);
}
protected override void OnStart(string[] args)
{
SetTimer();
}
protected override void OnStop()
{
oTimer.Stop();
}
对存储过程的调用如下:
public DataSet getCustomerDetails()
{
DateTime First_Date = DateTime.Now;
DateTime dateOnly = First_Date.Date;
DateTime First_Date1 = dateOnly.AddDays(-1); // assign back to see the new instance
DateTime End_Date = DateTime.Now;
SqlConnection oSqlConnection = new SqlConnection(strConn);
oSqlConnection.Open();
SqlCommand oSqlCommand = new SqlCommand();
oSqlCommand.CommandTimeout = 0;
oSqlCommand.CommandType = CommandType.StoredProcedure;
oSqlCommand.CommandText = "Daily_Airtime_Summary";
oSqlCommand.Parameters.Add(new SqlParameter("@StartDate", SqlDbType.DateTime)).Value = First_Date1;
oSqlCommand.Parameters.Add(new SqlParameter("@EndDate", SqlDbType.DateTime)).Value = End_Date;
oSqlCommand.Connection = oSqlConnection;
DataSet ds = new DataSet();
SqlDataAdapter oSqlDataAdapter = new SqlDataAdapter(oSqlCommand);
oSqlDataAdapter.Fill(ds);
oSqlConnection.Close();
return ds;
}
我面临的问题:
once
。但是,当我检查table B
时,我看到相同的数据被填充了近17次。start date = yesterday's date
和end date = today's date
。但是,一旦提取start date = today's date
和start date = yesterday's date
的日期(多次),我会看到该过程在end date = today's date
时继续运行。有人可以在这里指导吗?
答案 0 :(得分:0)
检查逻辑是否有时间运行proc。这可能无法正确初始化,导致初始启动时的proc torrun。
另外,要调试它,您需要使用安装作为服务安装。用于指向项目中调试版本的服务可执行文件的Net实用程序。在调试模式下编译,使用控制面板中的Windows服务实用程序启动服务,然后在Visual Studio中附加到该进程。