1

Take a look at my code:

Timer myTimer = new Timer { Interval = 1000 };
public void button_Click(object sender, EventArgs e)
{
    myTimer.Tick += new EventHandler(OnTick);
    myTimer.Start();
}
public void OnTick(object sender, EventArgs ea)
{
    myTimer.Stop();
    Execute();
}

I want the function Execute(); to run everyday at specify time, ex: 1h:5min, 1h:25min, 2h10min.... I use the Timer but I only can make the function run every Interval time. How do I specify an absolute time for the Timer?

zebediah49
  • 7,467
  • 1
  • 33
  • 50
vyclarks
  • 854
  • 2
  • 15
  • 39
  • Assuming your application will be running all the time, you could write some sort of `AlarmClock` class, that maintains a list of delegates, and times to call them. Internally a timer would periodically fire, checking to see if it is time to call any of the delegates yet. – Jonathon Reinhart Jul 11 '13 at 04:21
  • 1
    This may be helpful for you http://stackoverflow.com/questions/3243348/how-to-call-a-method-daily-at-specific-time-in-c – Khadim Ali Jul 11 '13 at 04:24
  • 2
    I recommend using Windows Scheduled Tasks. How else are you going to ensure that your app is even *running* at that time? – Cody Gray - on strike Jul 11 '13 at 05:03

3 Answers3

1

You could calculate the number of milliseconds to elapse between the current time and the time at which the Timer should run when your application starts. Set the number of milliseconds for the timer's Interval.

Example:

TimeSpan ts = <datetime when timer should fire> - DateTime.Now;

myTimer.Tick += new EventHandler(OnTick);
myTimer.Interval = ts.TotalMilliseconds;
myTimer.Start();

When the timer has fired, set the interval again using the above line to make sure it fires again the next day at the specified time.

This of course assumes that your application really runs at the time you want to timer to fire.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
0

You can create schedules using Quartz.net scheduler: http://quartznet.sourceforge.net/

Nitin Sawant
  • 7,278
  • 9
  • 52
  • 98
0

You cannot specify an absolute time for any of the built in timer classes. You must calculate the interval manually.

Other solutions that may be appropriate for you:

  • Use a scheduler like Quartz
  • Use a windows scheduled task
user2509738
  • 219
  • 1
  • 6