Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Service run every hour in specific minute

I need help. I have Windows Service and I need run this service every hour in specific minute for example: 09:05, 10:05, 11:05,.... My service now start every hour but every hour from time when i start this service. So how can I achieve my needs.

My code:

public partial class Service1 : ServiceBase
{
    System.Timers.Timer timer = new System.Timers.Timer();

    public Service1()
    {
        InitializeComponent();
    }

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

        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

        timer.Interval = 60000;

        timer.Enabled = true;
    }

    protected override void OnStop()
    {
        timer.Enabled = false;

        this.WriteToFile("Stopping Service {0}");
    }

    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        this.WriteToFile(" interval start {0}");
    } }
like image 920
Marko Avatar asked Mar 27 '17 07:03

Marko


1 Answers

You should check current time every 'n' seconds (1 as example) from timer:

public partial class Service1 : ServiceBase
{
    System.Timers.Timer timer = new System.Timers.Timer();

    public Service1()
    {
        InitializeComponent();
    }

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

        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

        timer.Interval = 1000; // 1000 ms => 1 second

        timer.Enabled = true;
    }

    protected override void OnStop()
    {
        timer.Enabled = false;

        this.WriteToFile("Stopping Service {0}");
    }

    private int lastHour = -1;
    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        var curTime = DateTime.Now; // Get current time
        if (lastHour != curTime.Hour && curTime.Minute == 5) // If now 5 min of any hour
        {
            lastHour = curTime.Hour;

            // Some action
            this.WriteToFile(" interval start {0}");
        }
    } 
}
like image 191
Ivan Kishchenko Avatar answered Sep 17 '22 22:09

Ivan Kishchenko