【问题标题】:How to get a system date change notification in .NET core on linux?如何在 Linux 上的 .NET 核心中获取系统日期更改通知?
【发布时间】:2019-05-22 16:04:57
【问题描述】:

我正在尝试在 .NET core/Standard 中获取通知事件(因为我需要计划未来的操作)。我正在将一段现有的 .NET4.5x 代码移植到 .NET core 2.2 或 .NETStandard2。

最初我使用的是:

SystemEvents.TimeChanged += SystemEvents_TimeChanged; //my handler

但在 .NETCore 或 .NETStandard 中,this is not implemented

克服这个问题的最优雅的方法是什么?

【问题讨论】:

    标签: events .net-core .net-standard systemevent


    【解决方案1】:

    好的,所以最后我是这样做的(伪代码):

    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();
            }
        }
    }
    

    但这仅适用于手动时间更改,不适用于夏令时或时区更新!

    【讨论】:

      猜你喜欢
      • 2019-08-26
      • 1970-01-01
      • 2022-01-25
      • 2019-09-19
      • 2022-08-17
      • 1970-01-01
      • 2011-08-14
      • 1970-01-01
      • 2019-08-28
      相关资源
      最近更新 更多