events.net-core.net-standardsystemevent

How to get a system date change notification in .NET core on linux?


I'm trying to get a notification event in .NET core/Standard (as I need to do plan future actions). I'm porting a piece of existing .NET4.5x code to .NET core 2.2 or .NETStandard2.

Originally I was using:

SystemEvents.TimeChanged += SystemEvents_TimeChanged; //my handler

But in .NETCore or .NETStandard, this is not implemented.

What is the most elegant way to overcome that?


Solution

  • OK, so finally I did it that way (pseudo code):

    public TimeSpan CheckInterval { get; private set; } = TimeSpan.FromMinutes(1);
    public TimeSpan MaxAllowedDeviation { get; private set; } = TimeSpan.FromSeconds(1);
    
    private async Task CheckTimeUpdate()
    {
        while (cancelToken.IsCancellationRequested == false)
        {
            DateTimeOffset beforeTimer = DateTimeOffset.Now;
    
            await Task.Delay(CheckInterval, cancelToken);
    
            DateTimeOffset afterTimer = DateTimeOffset.Now;
    
            if ((afterTimer.UtcDateTime - beforeTimer.UtcDateTime).Duration() > MaxAllowedDeviation + CheckInterval)
            {
                //raises the event
                TimeChanged?.Invoke();
            }
        }
    }
    

    But this only works for manual time change, not for daylight saving nor time zone updates!!