Windows service scheduling to run daily once a day at 6:00 AM

后端 未结 6 2033
無奈伤痛
無奈伤痛 2020-12-10 03:17

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()
         


        
相关标签:
6条回答
  • 2020-12-10 03:57

    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();
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-10 03:59

    If a service is really required, look at Quartz.NET to do the scheduling for you

    http://www.quartz-scheduler.net/

    0 讨论(0)
  • 2020-12-10 04:04

    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

    0 讨论(0)
  • 2020-12-10 04:10

    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
        }
    
    0 讨论(0)
  • 2020-12-10 04:20

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-10 04:22

    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.

    0 讨论(0)
提交回复
热议问题