Search code examples
c#windows-services

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


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()
{
    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);
    }
}

In the above code you can see that in OnStart Method of service i am calling a Function ExtractDataFromSharePoint(). How i will schedule this to run daily morning at 6:00 AM.


Solution

  • 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