I want to wait for x hours before executing some code in C#. i thought using a timer would be a good idea. (using thread.sleep does not seem right). But it just does not work. i am using the following code:
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = x * 3600000;
timer.Enabled = true;
timer.Elapsed += (o, e) => SomeFunction(username);
timer.AutoReset = true;
timer.Start();
}
this code supposed to wait for x hours and then execute SomeFunction but when i debug it, the main function ends after timer.start().
do you see any problem here? or can you suggest an alternative besides thread.sleep or await Task.Delay() ?
System.Timers.Timernormally uses a background thread to raise the event, so it will start the timer and then move on, it does not block.Mainexits - there's no code in it aftertimer.Start();. So if your application has nothing else to do,Thread.Sleepisn't really any worse than using a timer. That said, it's still a bad idea to use a timer (orThread.Sleep) for this. Why not use e.g. windows task scheduler instead? What are you actually trying to do? Why do you want to run an application that only does something hours after it's launched?