使用Rx .Net在不活动后执行一种方法

时间:2019-06-17 13:29:56

标签: .net asp.net-core system.reactive asp.net-core-webapi mediatr

我有一个这样的控制器动作:

[HttpPost("Post")]
public async Task Post([FromBody] UpdateDataCommand command)
{
    await _mediator.Send(command);
}

这是在.Net Core中完成的,并且正在使用MediatR处理命令。

现在, UpdateDataCommand 具有一个整数的 StationId 属性,用于标识站号。 客户端应用程序通过执行Post调用此方法时,将更新数据库中的数据。 我想使用Rx .Net进行的工作是在Await _mediator.Send(command)之后启动计时器。计时器将设置为1分钟。 1分钟后,我想调用另一个方法,该方法将在数据库中设置该标志,但仅为此StationId设置。如果有人使用相同的StationId进行发布,则计时器应自行重置。

伪代码中的代码如下:

[HttpPost("Post")]
public async Task Post([FromBody] UpdateDataCommand command)
{
    int stationId = command.StationId;
    // let's assume stationId==2

    //saves data for stationId==2
    await _mediator.Send(command);

    //Start a timer of 1 min
    //if timer fires (meaning the 1 minute has passed) call Method2();
    //if client does another "Post" for stationId==2 in the meantime 
      (let's say that the client does another "Post" for stationId==2 after 20 sec)
      then reset the timer
}

如何使用.Net中的Reactive Extensions来做到这一点?

更新(@Enigmativity): 它仍然不起作用,我将计时器设置为10秒,如果您查看输出时间,您会发现我在09:17:49上发布了一个帖子(启动了10秒钟的计时器),然后我做了在09:17:55的新帖子(已经启动了另一个计时器,但是它应该只重置了旧计时器),并且在第一个调用后10秒钟和第二个调用后另一个10秒钟启动了计时器。 : Application output

2 个答案:

答案 0 :(得分:1)

我无法对此进行测试,但是我认为这非常接近:

private Subject<UpdateDataCommand> posted = new Subject<UpdateDataCommand>();

private void PostInitialize()
{
    posted
        .GroupBy(x => x.StationId)
        .Select(gxs =>
            gxs
                .Select(x =>
                    Observable
                        .Timer(TimeSpan.FromMinutes(1.0))
                        .Select(_ => x))
                .Switch())
        .Merge()
        .Subscribe(stationId =>
        {
            /* update database */
        });
}

public async Task Post(UpdateDataCommand command)
{
    int stationId = command.StationId;
    await _mediator.Send(command);
    posted.OnNext(command);
}

让我知道是否可以关闭它。

在开始发布更新数据命令之前,您必须调用PostInitialize进行设置。


下面的测试表明此方法有效:

var rnd = new Random();

var posted =
    Observable
        .Generate(
            0, x => x < 20, x => x + 1, x => x,
            x => TimeSpan.FromSeconds(rnd.NextDouble()));

posted
    .GroupBy(x => x % 3)
    .Select(gxs =>
        gxs
            .Select(x =>
                Observable
                    .Timer(TimeSpan.FromSeconds(1.9))
                    .Select(_ => x))
            .Switch())
    .Merge()
    .Subscribe(x => Console.WriteLine(x));

我得到如下结果:

3
4
14
15
17
18
19

自从我使用.GroupBy(x => x % 3)以来,它将始终输出171819-但如果随机间隔足够大,则将输出较早的数字。 / p>

答案 1 :(得分:0)

要使用Rx.Net启动计时器,我们可以调用:

var subscription = Observable.Timer(TimeSpan.FromSeconds(timeout))
    .Subscribe(
        value =>{    /* ... */ }
    );

要取消此订阅,​​我们只需要稍后处理此订阅:

subscription.Dispose();

问题在于如何保留订阅。一种方法是创建一个SubscriptionManager服务(单个),因此我们可以调用这样的服务来调度任务,然后稍后在控制器动作中取消它,如下所示:

// you controller class

    private readonly ILogger<HomeController> _logger;       // injected by DI
    private readonly SubscriptionManager _subscriptionMgr;  // injected by DI


    public async Task Post(...)
    {
        ...
        // saves data for #stationId
        // Start a timer of 1 min
        this._subscriptionMgr.ScheduleForStationId(stationId);    // schedule a task that for #stationId that will be executed in 60s
    }


    [HttpPost("/Command2")]
    public async Task Command2(...)
    {
        int stationId =  command.StationId;
        if( shouldCancel ){
            this._subscriptionMgr.CancelForStationId(stationId);  // cancel previous task for #stationId
        }
    }

如果您想在内存中管理订阅,我们可以使用ConcurrentDictionary来存储订阅:

public class SubscriptionManager : IDisposable
{
    private ConcurrentDictionary<string,IDisposable> _dict;
    private readonly IServiceProvider _sp;
    private readonly ILogger<SubscriptionManager> _logger;

    public SubscriptionManager(IServiceProvider sp, ILogger<SubscriptionManager> logger)
    {
        this._dict= new ConcurrentDictionary<string,IDisposable>();
        this._sp = sp;
        this._logger = logger;
    }

    public IDisposable ScheduleForStationId(int stationId)
    {
        var timeout = 60;
        this._logger.LogWarning($"Task for Station#{stationId} will be exexuted in {timeout}s") ;
        var subscription = Observable.Timer(TimeSpan.FromSeconds(timeout))
            .Subscribe(
                value =>{  
                    // if you need update the db, create a new scope:
                    using(var scope = this._sp.CreateScope()){
                        var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
                        var station=dbContext.StationStatus.Where(ss => ss.StationId == stationId)
                            .FirstOrDefault();
                        station.Note = "updated";
                        dbContext.SaveChanges();
                    }
                    this._logger.LogWarning($"Task for Station#{stationId} has been executed") ;
                },
                e =>{
                    Console.WriteLine("Error!"+ e.Message);
                }
            );
        this._dict.AddOrUpdate( stationId.ToString(), subscription , (id , sub)=> {
            sub.Dispose();       // dispose the old one
            return subscription;
        });
        return subscription;
    }

    public void CancelForStationId(int stationId)
    {
        IDisposable subscription = null;
        this._dict.TryGetValue(stationId.ToString(), out subscription);
        this._logger.LogWarning($"Task for station#{stationId} has been canceled");
        subscription?.Dispose();

        // ... if you want to update the db , create a new scope
        using(var scope = this._sp.CreateScope()){
            var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
            var station=dbContext.StationStatus.Where(ss => ss.StationId == stationId)
                .FirstOrDefault();
            station.Note = "canceled";
            dbContext.SaveChanges();
            this._logger.LogWarning("The db has been changed");
        }
    }

    public void Dispose()
    {
        foreach(var entry in this._dict){
            entry.Value.Dispose();
        }
    }
}

另一种方法是为任务管理器(如cron)创建平面记录,但它根本不会使用Rx.NET。