每分钟都会调用一些 C# 方法(asp.net Web API Web)



我必须每分钟运行一个C#方法。我确实为计时器创建了一个observable并每 1 分钟调用一次它,我在类构造函数中使用了这段代码。还有其他解决方案吗?

public Test()
{
    IObservable<long> timer = Observable
        .Defer(() =>
    {
        var now = DateTimeOffset.Now;
        var result = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, 0, 0, now.Offset);
        result = result.AddMinutes(((now.Minute / 1) + 1) * 1);
        return Observable.Timer(result, TimeSpan.FromMinutes(1.0));
    });
    timer.Subscribe(async x =>
    {
        await InvokeMethod().ConfigureAwait(false);
    });
}
在我看来

,这就是你需要的:

public void Test()
{
    IObservable<Unit> timer =
        Observable
            .Defer(() =>
            {
                var now = DateTimeOffset.Now;
                var result = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute + 1, 0, now.Offset);
                return Observable.Timer(result, TimeSpan.FromMinutes(1.0));
            })
            .SelectMany(x => Observable.FromAsync(() => InvokeMethod()));
    timer.Subscribe();
}

请记住,这会随着时间的推移而漂移,并且不会每分钟都触发。您每次都需要重新调整。使用Observable.Generate会更好。


public void Test()
{
    IObservable<Unit> timer =
        Observable
            .Generate(
                new { now = DateTimeOffset.Now, count = 0 },
                t => true,
                t => new { t.now, count = t.count + 1 },
                t => t.count,
                t => t.now.AddMinutes(t.count))
            .SelectMany(x => Observable.FromAsync(() => InvokeMethod()));
    timer.Subscribe();
}

相关内容

  • 没有找到相关文章

最新更新