Blazor wasm 中的周期性后台任务

Jen*_*s B 2 blazor blazor-webassembly

在 Blazor wasm 中,我想定期执行一个作业(代码),即使用户正在浏览页面(例如每 x 分钟)。

那可能吗?什么是实用的方法?

Nei*_*l W 5

创建一个服务来管理计时器

public class JobExecutedEventArgs : EventArgs {}


public class PeriodicExecutor : IDisposable
{
    public event EventHandler<JobExecutedEventArgs> JobExecuted;
    void OnJobExecuted()
    {
        JobExecuted?.Invoke(this, new JobExecutedEventArgs());
    }

    Timer _Timer;
    bool _Running;

    public void StartExecuting()
    {
        if (!_Running)
        {
            // Initiate a Timer
            _Timer= new Timer();
            _Timer.Interval = 300000;  // every 5 mins
            _Timer.Elapsed += HandleTimer;
            _Timer.AutoReset = true;
            _Timer.Enabled = true;

            _Running = true;
        }
    }
    void HandleTimer(object source, ElapsedEventArgs e)
    {
        // Execute required job

        // Notify any subscribers to the event
        OnJobExecuted();
    }
    public void Dispose()
    {
        if (_Running)
        {
            // Clear up the timer
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Program.cs 中注册

builder.Services.AddSingleton<PeriodicExecutor>();
Run Code Online (Sandbox Code Playgroud)

请求它并在主页初始化中启动它

@page "/home"
@inject PeriodicExecutor PeriodicExecutor

@code {
    protected override void OnInitialized()
    {
        PeriodicExecutor.StartExecuting();
    }
}
Run Code Online (Sandbox Code Playgroud)

在任何组件中,如果您想在作业执行时做某事

@inject PeriodicExecutor PeriodicExecutor
@implements IDisposable

<label>@JobNotification</label>

@code {

   protected override void OnIntiialized()
   {
       PeriodicExecutor.JobExecuted += HandleJobExecuted;
   }
   public void Dispose()
   {
       PeriodicExecutor.JobExecuted -= HandleJobExecuted;
   }

   string JobNotification;
   void HandleJobExecuted(object sender, JobExecutedEventArgs e)
   {
        JobNotification = $"Job Executed: {DateTime.Now}";
   }
}
Run Code Online (Sandbox Code Playgroud)