Home > Enterprise >  Generic and clean way to execute a method only after a certain period of time
Generic and clean way to execute a method only after a certain period of time

Time:03-15

Let's say every PeriState method is called a 100 time per second. I'd like to execute PeriState_A method only once a day after the first occurrence, and PeriState_B once a hour after the first occurrence and so on. What is the cleanest, generic way to do this. I don't necessarily need coding example. A hint or a pattern name might help as well. So my goal here is to keep the code clean as possible and source the time management in a separate file.

PeriState_A
01/01/2022 10:00 -> Write log.
01/01/2022 11:00 -> Ignore
01/01/2022 22:00 -> Ignore
02/01/2022 09:50 -> Ignore
02/01/2022 10:10 -> Write log.

See code below.

private DateTime periStateA_called;

static void Main(string[] args)
{
    var program = new Program();
    program.Startup();
    Console.ReadLine();
}

private void Startup()
{
    var appleTimer = new Timer(1000);
    var bananaTimer = new Timer(1500);
    var cranberriesTimer = new Timer(2000);
    appleTimer.Elapsed  = PeriState_A;
    appleTimer.Interval = 1000;
    appleTimer.Enabled = true;
}

private void PeriState_A(object? source, ElapsedEventArgs e)
{
    if (periStateA_called < DateTime.Now - TimeSpan.FromHours(24)) {
        Console.WriteLine("PeriState_A");
        periStateA_called = DateTime.Now;
    }
}

private static void PeriState_B(object? source, ElapsedEventArgs e)
{
    Console.WriteLine("PeriState_B");
}

private static void PeriState_C(object? source, ElapsedEventArgs e)
{
    Console.WriteLine("PeriState_C");
}

CodePudding user response:

It's best to use Windows' scheduled tasks. You can call the function as the initial parameter.

CodePudding user response:

Try this:

private DateTime EventAPrevRun = DateTime.Now.AddHours(-1);
private DateTime EventBPrevRun = DateTime.Now.AddDays(-1); 
//this should run only one hour 
public void EventA()
{
    if(EventAPrevRun < DateTime.Now.AddHours(-1))
{
    EventAPrevRun = DateTime.Now;
    //Do stuff
}

}
//this should run only one day
public void EventB()
{
   if(EventBPrevRun < DateTime.Now.AddDays(-1))
   {
    EventBPrevRun = DateTime.Now;
    //do stuff
   }
}
  • Related