I am trying to do an repeated method call with Timer
class.
I can get it work as I want if I have ReadKey
in the main. I'm wondering why is that and is there a workaround or a better way to do this.
I do want my program to exit once the scheduled work is done.
My whole test program looks like this:
using System;
using System.Threading;
namespace TestProgram
{
public class Program
{
static void Main(string[] args)
{
int periodInSeconds = 3;
double durationInMinutes = 0.5;
var scheduler = new ActionScheduler(periodInSeconds, durationInMinutes, Work);
scheduler.Run();
Console.ReadKey();
}
static void Work()
{
Console.WriteLine(DateTime.Now + ": Doing work...");
}
private class ActionScheduler
{
private Timer Timer;
private DateTime StopTime;
private int PeriodInSeconds { get; set; }
private double DurationInMinutes { get; set; }
private Action Action { get; set; }
public ActionScheduler(int periodInSeconds, double durationInMinutes, Action method)
{
PeriodInSeconds = periodInSeconds;
DurationInMinutes = durationInMinutes;
Action = method;
}
public void Run()
{
StopTime = DateTime.Now.AddMinutes(DurationInMinutes);
Timer = new Timer(TimerCallback, null, 0, PeriodInSeconds * 1000);
}
private void TimerCallback(object state)
{
if (DateTime.Now >= StopTime)
{
Timer.Dispose();
}
Action();
}
}
}
}