BTOM
BTOM

Reputation: 73

About page updates on Blazor Server

Sorry for the very rudimentary question.

I'm writing a simple management app for production equipment on Blazor Server. I want to view that data on the Blazor page as the number of completed pieces is updated from the production equipment to the database every second.

Specifically, I want to refresh the page once the database is refreshed, or every few seconds (for example, every 10 seconds).

However, I have no idea how to make either of these. How should this be considered and implemented?

I'm sorry for the very abstract question, but I would like some advice. Thank you.

Upvotes: 1

Views: 628

Answers (1)

Kevin
Kevin

Reputation: 26

So unless there is an event published from your database that your app can listen to, then you will need to query the database on a set interval.

This solution would fit your situation as well: Blazor Timer call async API task to update UI

Essentially you will set a timer. Here is Microsoft's general documentation: https://learn.microsoft.com/en-us/dotnet/api/system.threading.timer?view=net-5.0

What this looks like practically is that when the Component Initializes, you will put your code.

I personally had the following in the @code section:

private System.Timers.Timer DelayTimer;

async void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    await CheckForNotifications();
}

async Task CheckForNotifications()
{
    // Your Code goes here.
    StateHasChanged();
}

protected override async Task OnInitializedAsync()
{
    _log.Information("Component is Initialized.");
    await CheckForNotifications();

    DelayTimer = new System.Timers.Timer((double)(60 * 1000 * 3)); // 60 seconds * 3 is 3 minutes.
    DelayTimer.Elapsed += timer_Elapsed;
    DelayTimer.AutoReset = true;
    DelayTimer.Start();
    _log.Debug("Timer Started.");

}

Upvotes: 1

Related Questions