asp.net core 定时任务 使用SignalR推送消息 前端vue 接收并显示消息

ASP.NET Core中有一个名为Quartz.NET的第三方定时任务调度框架,使用它可以方便地实现定时任务。同时,ASP.NET Core还提供了SignalR框架,用于实现实时通信功能。在Vue中,可以使用Vue-CLI来创建项目,并使用Vue.js框架开发前端应用程序。下面是实现你所需功能的大致步骤:

1. 确认ASP.NET Core项目中已添加Quartz.NET和SignalR的NuGet包。可以在项目的.csproj文件中手动添加这些包,如下所示:

```xml
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0"/>
<PackageReference Include="Quartz" Version="3.0.7"/>
</ItemGroup>
```

2. 创建定时任务。在Quartz.NET中,需要实现IJob接口并编写任务逻辑。例如:

```csharp
public class MyJob : IJob
{
private readonly IHubContext<MyHub> _hubContext;

public MyJob(IHubContext<MyHub> hubContext)
{
_hubContext = hubContext;
}

public Task Execute(IJobExecutionContext context)
{
// 在此处编写业务逻辑
// 使用SignalR推送消息给前端页面
return _hubContext.Clients.All.SendAsync("broadcastMessage", "定时任务消息");
}
}
```

3. 在Startup.cs文件中注入IJob和IHubContext,用于任务的调度和SignalR的消息发送。例如:

```csharp
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// 注册Quartz.NET服务
services.AddSingleton<IJobFactory, SingletonJobFactory>();
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
services.AddSingleton<MyJob>(); // 将任务注入容器

var jobKey = new JobKey("myJob");
services.AddSingleton(new JobRegistration(
jobType: typeof(MyJob),
jobKey: jobKey,
expression: "0/10 * * * * *" // 表示每10秒执行一次
));

services.AddSingleton(sp =>
{
var scheduler = sp.GetService<ISchedulerFactory>().GetScheduler().Result;
scheduler.JobFactory = sp.GetService<IJobFactory>();
var registration = sp.GetService<JobRegistration>();
var job = JobBuilder.Create<MyJob>()
.WithIdentity(registration.JobKey)
.Build();

var trigger = TriggerBuilder.Create()
.WithIdentity("myTrigger")
.WithCronSchedule(registration.Expression)
.StartNow()
.Build();

scheduler.ScheduleJob(job, trigger).Wait();
scheduler.Start().Wait();
return scheduler;
});

// 注册SignalR服务
services.AddSignalR();

services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MyHub>("/myhub"); // 注册SignalR Hub
endpoints.MapControllers();
});
}
}
```

4. 在前端页面中,使用Vue.js框架开发应用程序,以接收和显示由SignalR推送的消息。例如:

```javascript
<script>
import * as signalR from "@microsoft/signalr";

export default {
name: "app",
data() {
return {
messages: []
};
},
mounted() {
// 连接SignalR服务端
let connection = new signalR.HubConnectionBuilder()
.withUrl("/myhub")
.build();
connection.start().catch((err) => console.error(err.toString()));

// 接收消息
connection.on("broadcastMessage", (message) => {
this.messages.unshift(message);
});
}
};
</script>

<template>
<div>
<h1>Messages</h1>
<ul>
<li v-for="(message, index) in messages" :key="index">{{message}}</li>
</ul>
</div>
</template>
```

这样,当定时任务执行时,将会向所有连接到SignalR Hub的客户端(包括Vue前端应用程序)发送消息。前端应用程序将消息存储在Vue组件中的messages数组中,并在页面上显示。

posted @ 2023-04-26 17:03  秋风野马  阅读(517)  评论(0编辑  收藏  举报