2

I am using C# and I want to create an event that display a field to the user after 24 hours after it is been filled up. Meaning when the field is filled up I have to wait 24 hours before I display it to the user. Is there any simple way to do so? I didn't write any code yes since examples I found on line where suggesting timers and it doesn't resemble my problem.
I'm using .NET 3.5

Mindan
  • 979
  • 6
  • 17
  • 37

2 Answers2

1

This sample code (Console application) demonstrates when property value changed, then after 24 hour calls method to showing data:

public class Program
{
    private CancellationTokenSource tokenSource;
    private string _myProperty;
    public string MyProperty
    {
        get
        {
            return _myProperty; 
        }
        set
        {
            _myProperty = value;
            _ = Run(() => SendToUser(_myProperty), TimeSpan.FromHours(24), tokenSource.Token);
        }
    }
    private static void Main()
    {
        var prg = new Program();
        prg.tokenSource = new CancellationTokenSource();
        prg.MyProperty = "Test test";
        Console.ReadLine();
    }
    private void SendToUser(string data)
    {
        //Display data for user
        Console.WriteLine(data);
    }
    public static async Task Run(Action action, TimeSpan period, CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            await Task.Delay(period, cancellationToken);

            if (!cancellationToken.IsCancellationRequested)
                action();
        }
    }

    public static Task Run(Action action, TimeSpan period)
    {
        return Run(action, period, CancellationToken.None);
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Mansur Kurtov
  • 726
  • 1
  • 4
  • 12
0

In .NET 3.5:

public class Program
{
    private string _myProperty;
    public string MyProperty
    {
        get
        {
            return _myProperty; 
        }
        set
        {
            _myProperty = value;
            ExecuteAfter(() => SendToUser(_myProperty), TimeSpan.FromHours(24));
        }
    }
    private static void Main()
    {
        var prg = new Program();
        prg.MyProperty = "Test test";
        Console.ReadLine();
    }
    private void SendToUser(string data)
    {
        //Display data for user
        Console.WriteLine(data);
    }
    public static void ExecuteAfter(Action action, TimeSpan delay)
    {
        Timer timer = null;
        timer = new System.Threading.Timer(s =>
        {
            action();
            timer.Dispose();
         }, null, (long)delay.TotalMilliseconds, Timeout.Infinite);
    }
}

or use FluentScheduler - ready nuget task scheduler package, https://www.nuget.org/packages/FluentScheduler/3.1.46

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Mansur Kurtov
  • 726
  • 1
  • 4
  • 12