-1

So, imagine I have a status of an entity. I want to change that status and then change it back after a certain period of time. For instance, I want to rent something for 5 hours, so I make a request to create a new rent order entry and, say, update the status of an item to InRent. Therefore, after 5 hours I want the status to be automatically changed to InStock.

I know, it can be implemented on a GET request, the next time someone is trying to fetch the data, regarding these statuses. But is there a better approach? Thanks in advance:)

UPD: The second and the third options in Zhi Lv's answer are what I was asking for. Thank you:)

1 Answers1

0

As SvyatoslavDanyliv said, you could add a new DateTime column: RentExpiration. Then compare it with current time and based on the result to change the status.

When user rent the entity, you could change its status from InStock to InRent (the default status is InStock) and set the RentExpiration time.

Then, to update the status and the RentExpiration, you could use the following methods:

  1. Check and update the status in the Next request

    In the Next Request, before getting/listing the Entity, you could check whether the entity has RentExpiration time or not (via the EF Core DbContext), if it has RentExpiration time and the time is expired, change the status to InStock and reset or clear the RentExpiration time. If the entity doesn't have the RentExpiration, the status should be InStock and if the RentExpiration time not expired, the status should be InRent.

    After that, you could query the entity table and get the latest data (with status). Then, if you rent an entity, call the update method to change the status and set the RentExpiration time.

  2. Create a stored procedure to update the status based on the RentExpiration time, then create a SQL Server Agent job which will run the stored procedure every 5 minutes (or 10).

    The update status command like this:

    UPDATE RentTable SET Status = 'InStock' WHERE Status = 'InRent' AND RentExpiration < getdate() AND RentExpiration IS NOT NULL

    Then, you could refer the following links to create SQL Job:

    Create a Schedule
    Execute Stored Proc Using SQL Job

    By using this method, it will change the status on the SQL Server and the SQL Job will change the status automatically.

  3. Create a scheduler Background tasks/job to update the status.

    In the background job, query the database to get the entities (via the EF Core DbContext), then compare the RentExpiration time and based on the result to update the status.

    You could refer the following link to create background task in asp.net core application.

    Background tasks with hosted services in ASP.NET Core

    How to trigger .NET Core 3.1 Hosted Service at certain time?

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30