如何安排每天上午11点的Windows服务

本文关键字:Windows 服务 11点 何安排 每天 | 更新日期: 2023-09-27 17:53:11

我正在运行windows服务,该服务检查时间是否大于上午11点,如果在该日期没有特定报告类型的记录,则插入数据。计时器每10分钟设置一次。是否有其他的选择,因为我觉得有太多的数据库负载。

它检查EmailNotificationSentlog表,如果不存在该日期和该报告类型的记录,则插入数据。

Sno   ReportType  CreatedDate
1     Daily        2015-05-29 11:00:07.683
2     Daily        2015-06-01 11:00:08.317
3     Daily        2015-06-02 11:17:56.890

检查数据是否插入。

    CreatePROCEDURE [dbo].[sp_get_EmailNotificationSentLogExists]     
    (    
     @RptType nvarchar(50)    
    )    
    AS    
    BEGIN    
     Declare @Time nvarchar(50)    
     Declare @RetVal int     
     set @RetVal = 0    
     Set @Time = '11:00'    
     IF(CONVERT(VARCHAR(5), GETDATE(), 114) >= @Time)    
     BEGIN    
        IF not exists(select 1 from EmailnotificationSentLog where ltrim(rtrim(ReportType)) = @RptType    
      and  convert(date,CreatedDate) = convert(date,GETDATE()))    
     BEGIN       
      SET @RetVal = 1    
        END    
     END    
     select @RetVal    
    END 

插入记录程序

CreatePROCEDURE [dbo].[sp_Insert_EmailNotificationSentLog]  
(  
 @RptType nvarchar(50)  
)  
AS  
BEGIN  
IF NOT EXISTS( select 1 from EmailNotificationSentLog where ReportType = @RptType 
    and cast(createddate as date) = CAST(getdate() as date))
BEGIN
   INSERT INTO EmailNotificationSentLog(ReportType,CreatedDate)values (@RptType,getdate()) 
END 
END  

服务类:

        public partial class Service1 : ServiceBase
        {
            Timer timer1 = new Timer();
            SqlConnection objSqlCon = new  SqlConnection(ConfigurationManager.AppSettings["SqlConnection"].ToString());
            string objRetval = string.Empty;
            public Service1()
            {
                InitializeComponent();
            }
        protected override void OnStart(string[] args)
        {
            timer1.Interval = 600000; //10 mts
            timer1.Enabled = true;
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled = true;
            WriteLog("Test Windows Service");
        }
        private void timer1_Tick(object sender,ElapsedEventArgs e)
        {
            WriteLog("Test Job Done Sucessfully");
            // If Time greater than 11 and if record doesnt exists
            objRetval = RetrieveData(ReportType.Daily.ToString());
            if (objRetval == "1")
            {
                InsertData();
            }
            //OnStop();
        }
        protected override void OnStop()
        {
            timer1.Enabled = false;
            WriteLog("Test Job Stopped Sucessfully");
        }
        public string RetrieveData(string strRptType)
        {
            string strRetVal = string.Empty;
            try
            {
                SqlCommand cmd = new SqlCommand("sp_get_EmailNotificationSentLogExists", objSqlCon);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@RptType", strRptType);
                if (objSqlCon.State != ConnectionState.Open)
                {
                    objSqlCon.Open();
                }
                strRetVal = Convert.ToString(cmd.ExecuteScalar());
                //l1.WriteLog("Data Inserted Successfully");
            }
            catch (Exception ex)
            {
                //l1.WriteLog(ex.Message.ToString());
                throw ex;
            }
            finally
            {
                objSqlCon.Close();
            }
            return strRetVal;
        }
        void InsertData()
        {
            try
            {
                SqlCommand cmd = new SqlCommand("sp_Insert_EmailNotificationSentLog", objSqlCon);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@RptType", ReportType.Daily.ToString());
                if (objSqlCon.State != ConnectionState.Open)
                {
                    objSqlCon.Open();
                }
                cmd.ExecuteNonQuery();
                WriteLog("Data Inserted Successfully");
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message.ToString());
                throw ex;
            }
            finally
            {
                objSqlCon.Close();
            }
        }
        public void WriteLog(string strMessage)
        {
            string strLogDir = string.Empty, strLogFileName = string.Empty, SstrFilePath = string.Empty;
            strLogDir = ConfigurationManager.AppSettings["LogDirectory"].ToString();
            strLogFileName = ConfigurationManager.AppSettings["Logname"].ToString();
            if (!Directory.Exists(strLogDir))
            {
                Directory.CreateDirectory(strLogDir);
            }
            SstrFilePath = strLogDir + "''" + strLogFileName;
            if (!File.Exists(SstrFilePath))
            {
                using (StreamWriter sw = File.CreateText(SstrFilePath))
                {
                    sw.WriteLine("================================================================================");
                    sw.WriteLine(" // " + DateTime.Now.ToString());
                    sw.WriteLine("Message 't't't: " + strMessage);
                    sw.Close();
                }
            }
            else
            {
                StreamReader sReder = new StreamReader(SstrFilePath);
                string oldText = sReder.ReadToEnd();
                sReder.Close();
                StreamWriter sWriter = new StreamWriter(SstrFilePath);
                sWriter.WriteLine(oldText);
                sWriter.WriteLine("================================================================================");
                sWriter.WriteLine(" // " + DateTime.Now.ToString());
                sWriter.WriteLine("File Name 't't't: " + strMessage);
                sWriter.Close();
            }
        }
        enum ReportType {Daily,Monthly,Yearly}
    }

如何安排每天上午11点的Windows服务

在windows中,您不需要手动检查运行任务的时间,有任务计划供您使用:

Open Task Scheduler by clicking the Start button , clicking Control Panel, clicking System and Security, clicking Administrative Tools, and then double-clicking Task Scheduler.‌   If you're prompted for an administrator password or confirmation, type the password or provide confirmation.
Click the Action menu, and then click Create Basic Task.
Type a name for the task and an optional description, and then click Next.
Do one of the following:
To select a schedule based on the calendar, click Daily, Weekly, Monthly, or One time, click Next; specify the schedule you want to use, and then click Next.
To select a schedule based on common recurring events, click When the computer starts or When I log on, and then click Next.
To select a schedule based on specific events, click When a specific event is logged, click Next; specify the event log and other information using the drop-down lists, and then click Next.
To schedule a program to start automatically, click Start a program, and then click Next.
Click Browse to find the program you want to start, and then click Next.
Click Finish.

http://windows.microsoft.com/en-au/windows/schedule-task 1 tc = windows 7