简体   繁体   中英

Windows Service Start at a specific time

I want the service to start once daily and then process the parser but it is not processing the files.

The date-time is equal to the scheduled time I want the process to begin. I have the parser on a different class and the parser works perfectly; I only have a problem with the scheduler as you can see below.

What is that I am missing to make the program starts at the specified time?

using System;
using System.ServiceProcess;
using System.IO;
using System.Threading;
using System.Configuration;
using ASRParserService.Services;

namespace ASRParserService
{
public partial class Service1 : ServiceBase
{
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        this.WriteToFile("Service started {0}");
        this.ScheduleService();
    }

    protected override void OnStop()
    {
        this.WriteToFile("Service stopped {0}");
        this.Schedular.Dispose();
    }
    private Timer Schedular;

    public void ScheduleService()
    {
        try
        {
            Schedular = new Timer(new TimerCallback(SchedularCallback));
            string mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
            this.WriteToFile("Service Mode: " + mode + " {0}");

            //Set the Default Time.
            DateTime scheduledTime = DateTime.MinValue;

            if (mode == "DAILY")
            {
                //Get the Scheduled Time from AppSettings.
                scheduledTime = DateTime.Parse(ConfigurationManager.AppSettings["ScheduledTime"]);
                if (DateTime.Now > scheduledTime)
                {
                    //If Scheduled Time is passed set Schedule for the next day.
                    scheduledTime = scheduledTime.AddDays(1);              
                }
                else if(DateTime.Now < scheduledTime)
                {
                    this.WriteToFile("Service scheduled has past the time");
                }
                else
                {
                    DownloadFromSFTP downloadFromSFTP = new DownloadFromSFTP();
                    UploadToSFTP uploadToSFTP = new UploadToSFTP();
                    DeleteLocalFiles deleteLocalFiles = new DeleteLocalFiles();
                }

            }

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

            this.WriteToFile("Service scheduled to run after: " + schedule + " {0}");

            //Get the difference in Minutes between the Scheduled and Current Time.
            int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);

            //Change the Timer's Due Time.
            Schedular.Change(dueTime, Timeout.Infinite);
        }
        catch (Exception ex)
        {
            WriteToFile("Service Error on: {0} " + ex.Message + ex.StackTrace);

            //Stop the Windows Service.
            using (ServiceController serviceController = new ServiceController("Service1"))
            {
                serviceController.Stop();
            }
        }
    }

    private void SchedularCallback(object e)
    {
        this.WriteToFile("Service Log: {0}");
        this.ScheduleService();
       
    }

    private void WriteToFile(string text)
    {
        string path = "C:\\EthiopianServices\\ServiceLog.txt";
        using (StreamWriter writer = new StreamWriter(path, true))
        {
            writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
            writer.Close();
        }
    }
  }
}

below is the app setting

<appSettings>
    <add key ="Mode" value ="Daily"/>
    <add key ="IntervalMinutes" value ="1"/>
    <add key ="ScheduledTime" value ="13:50"/>
</appSettings>

You don't describe what actually happens but, it looks like you will just always reschedule the timer because DateTime.Now will almost always be greater than scheduledTime.

The timer fires at scheduledTime but the clock will almost always advance before your code actually executes.

You only do your real work when DateTime.Now is equal to scheduledTIme and that will almost never happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM