Home > Net >  I want a function to only be allowed to call once a day
I want a function to only be allowed to call once a day

Time:11-04

Let's say its the 15th and my function runs, if that function is called again on the 15th it will not run. But if the date is the 16th and the function is called, then it is allowed to run. How could I achieve this? P.S. Code below is in visual basic however C# is fine for an answer

Private Sub CreateLogger()

    Logger = New CustomLogger(Sub(value, Type)
                                  Dim tempFileLogPath = IO.Path.Combine("C:\temp", $"FileAttributer_{Today:yyyyMMdd}.txt")
                                  Dim consoleLogger = New ConsoleLogger()
                                  Dim textFileLogger = New TextFileLogger(tempFileLogPath)
                                  Dim compositeLogger = New CompositeLogger(consoleLogger, textFileLogger)
                                  value = $"{DateTime.Now:dd/MM/yyyy HH:mm:ss} - {value}"
                                  compositeLogger.Write(value, Type)
                              End Sub)

End Sub

CodePudding user response:

I suppose this has to do with the file, so in the end you do not end up with multiple files per day.

You could do a check on the file to see if it was created before or not.

CodePudding user response:

I would store the last called time in a variable, and update it every time you call it. It doesn't need to include the time of day, just the date. Every time you call the function, check if the last called time is equal to the current date, and if it is return/throw error to stop the rest of the function.

CodePudding user response:

You have to save the last run time somewhere and compare the day every time.

This is a very simple example how to do it:

using System;
using System.Threading;
                    
public class Program
{
    private static DateTime lastRunTime;
    
    public static void Main()
    {
        for(int i=0; i < 10; i  ) {
            DoSomething();
            Thread.Sleep(1000);
        }
    }
    
    private static void DoSomething() 
    {
        if (DateTime.Now.Day != lastRunTime.Day) {
            lastRunTime = DateTime.Now;
            Console.WriteLine($"Run: {lastRunTime}");
        }       
    }
}

But I guess, Radu Hatos is right. You should better explain, why do you want you function to behave so.

  • Related