Andre Roque
Andre Roque

Reputation: 543

Running method at a specific time

I'm doing an application in Windows Forms (C#) and I want to set in the Layout an area where the user defines a given hour.

Then, when the user hit the "Start" button, every given hour a method is executed.

What is the easiest way to do this?

Upvotes: 2

Views: 2150

Answers (2)

LarsTech
LarsTech

Reputation: 81610

A simple WinForms Timer can get the job done:

DateTime runTime;

public Form1() {
  InitializeComponent();
  DateTime nowTime = DateTime.Now;
  runTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 12, 0, 0);
  timer1.Interval = 500;
}

void timer1_Tick(object sender, EventArgs e) {
  if (DateTime.Now > runTime) {
    timer1.Stop();
    MessageBox.Show("It's time!");
  }
}

void button1_Click(object sender, EventArgs e) {
  timer1.Start();
}

Simply update the runTime value with the hour and/or minute. The alarm will obviously not get triggered unless the program is running. As Hans noted, that would require a service.

Upvotes: 2

NeutronCode
NeutronCode

Reputation: 365

Not tested but something like this?

var timer = new System.Timers.Timer((DateTime.Now - (DateTime.Now - TimeSpan.FromHours(DateTime.Now.Hour + 1))).Milliseconds);
timer.Elapsed += (sender, evt) =>
{
    timer.Interval = (DateTime.Now - (DateTime.Now - TimeSpan.FromHours(DateTime.Now.Hour + 1))).Milliseconds;
    // Do things
};
timer.Start();

Upvotes: 0

Related Questions