Skip to content

Commit

Permalink
修复了QuartzNet定时任务 服务层注入到Job任务层时无法调起定时任务Bug
Browse files Browse the repository at this point in the history
  • Loading branch information
KawhiWei committed Dec 9, 2019
1 parent b04b50b commit 22ebe09
Show file tree
Hide file tree
Showing 8 changed files with 153 additions and 55 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -18,3 +18,4 @@
/Uwl.Admin/.vs
/Uwl.Admin/Uwl.ScheduledTask.Job/obj
/Uwl.Admin/Uwl.ScheduledTask.Job/bin
/Uwl.Admin/UwlAPI.Tools/appsettings.json
@@ -1,5 +1,6 @@
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
Expand All @@ -18,8 +19,10 @@ namespace Uwl.QuartzNet.JobCenter.Center
public class SchedulerCenterServer: ISchedulerCenter
{
private Task<IScheduler> _scheduler;
public SchedulerCenterServer()
private readonly IJobFactory _iocjobFactory;
public SchedulerCenterServer(IJobFactory jobFactory)
{
_iocjobFactory = jobFactory;
_scheduler = GetSchedulerAsync();
}
private Task<IScheduler> GetSchedulerAsync()
Expand All @@ -34,7 +37,7 @@ private Task<IScheduler> GetSchedulerAsync()
{ "quartz.serializer.type", "binary" },
};
StdSchedulerFactory factory = new StdSchedulerFactory(collection);
return _scheduler= factory.GetScheduler();
return _scheduler = factory.GetScheduler();
}
}

Expand All @@ -47,6 +50,7 @@ public async Task<JobResuleModel> StartScheduleAsync()
var result = new JobResuleModel();
try
{
this._scheduler.Result.JobFactory = this._iocjobFactory;
if (!this._scheduler.Result.IsStarted)
{
//等待任务运行完成
Expand Down
54 changes: 54 additions & 0 deletions Uwl.Admin/Uwl.QuartzNet.JobCenter/JobFactory/IOCJobFactory.cs
@@ -0,0 +1,54 @@
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Text;

namespace Uwl.QuartzNet.JobCenter.JobFactory
{
public class IOCJobFactory : IJobFactory
{
/// <summary>
/// 注入反射获取依赖对象
/// </summary>
private readonly IServiceProvider _serviceProvider;
public IOCJobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// 实现接口Job
/// </summary>
/// <param name="bundle"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
try
{
//个人测试目前没有内存泄漏等问题,若是各位大佬有上生产环境的 请监控一下内存情况
var serviceScope = _serviceProvider.CreateScope();
var job = serviceScope.ServiceProvider.GetService(bundle.JobDetail.JobType) as IJob;
return job;
//var job = _serviceProvider.GetService(bundle.JobDetail.JobType) as IJob;
//return job;

}
catch (Exception e)
{
throw e;
}
}

public void ReturnJob(IJob job)
{
var disposable = job as IDisposable;
if(disposable!=null)
{
disposable.Dispose();
}

}
}
}
30 changes: 22 additions & 8 deletions Uwl.Admin/Uwl.ScheduledTask.Job/TestJobOne.cs
@@ -1,23 +1,37 @@
using System;
using Quartz;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Quartz;
using Uwl.Common.Cache.RedisCache;
using Uwl.Common.Subscription;
using Uwl.Data.Server.MenuServices;

namespace Uwl.ScheduledTask.Job
{
public class TestJobOne : IJob
{
public async Task Execute(IJobExecutionContext context)
private readonly IRedisCacheManager _redisCacheManager;
private readonly IMenuServer _menuServer;
public TestJobOne(IRedisCacheManager redisCacheManager,IMenuServer menuServer)
{
this._redisCacheManager = redisCacheManager;
this._menuServer = menuServer;
}
public async Task Execute(IJobExecutionContext context)
{
//记录Job时间
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
await Console.Out.WriteLineAsync(string.Format("测试任务1:任务分组:{0},任务名称:{1}任务状态:{2}", context.JobDetail.Key.Group, context.JobDetail.Key.Name, "正常执行中"));

await Console.Out.WriteLineAsync("我是有Redis的注入测试任务");
var list = await _menuServer.GetMenuList();
await Console.Out.WriteLineAsync("菜单表里总数量" + list.Count.ToString());
stopwatch.Stop();
if (stopwatch.Elapsed.TotalMilliseconds > 0)
{
//写入日志性能监控表和执行是否出错
}
await Console.Out.WriteLineAsync("执行时间" + stopwatch.Elapsed.TotalMilliseconds);
//if (stopwatch.Elapsed.TotalMilliseconds > 0)
//{
// //写入日志性能监控表和执行是否出错
//}
}
}
}
5 changes: 5 additions & 0 deletions Uwl.Admin/Uwl.ScheduledTask.Job/Uwl.ScheduledTask.Job.csproj
Expand Up @@ -8,4 +8,9 @@
<PackageReference Include="Quartz" Version="3.0.7" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Uwl.Common\Uwl.Common.csproj" />
<ProjectReference Include="..\Uwl.Data.Server\Uwl.Data.Server.csproj" />
</ItemGroup>

</Project>
30 changes: 0 additions & 30 deletions Uwl.Admin/UwlAPI.Tools/Controllers/AuthorizeController.cs
Expand Up @@ -187,36 +187,6 @@ public async Task<MessageModel<dynamic>> TokenAssig([FromBody] LoginViewModel lo
var Ip = HttpContext.GetClientIP();
await Console.Out.WriteLineAsync(string.Format("客户端请求IP:{0}", Ip));
SysUser Info = await _userserver.CheckUser(loginViewModel.User, loginViewModel.Password);
#region QuartzNet定时任务
//await _schedulerCenter.AddScheduleJobAsync(new SysSchedule
//{
// Name = "test1",
// JobGroup = "test1group",
// AssemblyName = "Uwl.QuartzNet.JobCenter",
// ClassName = "Simple",
// RunTimes = 0,
// IntervalSecond =4,
//});
//await _schedulerCenter.AddScheduleJobAsync(new SysSchedule
//{
// Name = "testSimpleTwo",
// JobGroup = "test1group",
// AssemblyName = "Uwl.QuartzNet.JobCenter",
// ClassName = "Simple",
// RunTimes = 0,
// IntervalSecond = 9,
//});
//await _schedulerCenter.AddScheduleJobAsync(new SysSchedule
//{
// Name = "testSimpleThree",
// JobGroup = "test1group",
// AssemblyName = "Uwl.QuartzNet.JobCenter",
// ClassName = "Simple",
// RunTimes = 0,
// IntervalSecond = 5,
//});
//_rabbitMQ.SendData("hello", Info);
#endregion
if (Info == null)
{
data.msg = "账号或者密码错误";
Expand Down
80 changes: 65 additions & 15 deletions Uwl.Admin/UwlAPI.Tools/Startup.cs
Expand Up @@ -56,6 +56,12 @@
using Uwl.Common.SignalRMessage;
using Uwl.Common.Subscription;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Quartz.Spi;
using Uwl.QuartzNet.JobCenter.JobFactory;
using Uwl.ScheduledTask.Job;
using Quartz;
using Quartz.Impl;
using System.Reflection;

namespace UwlAPI.Tools
{
Expand Down Expand Up @@ -93,15 +99,15 @@ public void ConfigureServices(IServiceCollection services)
{

#region Cors跨域需要添加以下代码
services.AddCors(c =>
{
//控制器中[EnableCors("AllRequests")]名字需对应
c.AddPolicy(CorsName,
policy => policy
.AllowAnyOrigin()
.AllowAnyMethod()//允许任何方式
.AllowAnyHeader());//允许任何头//允许cookie
});
//services.AddCors(c =>
//{
// //控制器中[EnableCors("AllRequests")]名字需对应
// c.AddPolicy(CorsName,
// policy => policy
// .AllowAnyOrigin()
// .AllowAnyMethod()//允许任何方式
// .AllowAnyHeader());//允许任何头//允许cookie
//});

//services.AddCors(op =>
//{ op.AddPolicy("cors",
Expand Down Expand Up @@ -241,7 +247,7 @@ public void ConfigureServices(IServiceCollection services)
jwtSettings.Issuer,//发行人
jwtSettings.Audience,//听众
signingCredentials,//签名凭据
expiration:TimeSpan.FromSeconds(15*60)//过期时间
expiration:TimeSpan.FromSeconds(60*60)//过期时间
);
//No.1 基于自定义角色的策略授权
services.AddAuthorization(options =>
Expand Down Expand Up @@ -371,6 +377,8 @@ public void ConfigureServices(IServiceCollection services)
services.AddScoped<IScheduleRepositoty, DomainScheduleServer>();
//注入计划任务服务层
services.AddScoped<IScheduleServer, ScheduleServer>();
services.AddScoped<IScheduleServer, ScheduleServer>();
#endregion


#region 缓存和任务调度中心使用 单例模式注入生命周期
Expand All @@ -381,13 +389,50 @@ public void ConfigureServices(IServiceCollection services)
services.AddSingleton<IRabbitMQ, RabbitServer>();
//注入QuartzNet管理中心
services.AddSingleton<ISchedulerCenter, SchedulerCenterServer>();
services.AddSingleton<IJobFactory, IOCJobFactory>();
services.AddTransient<TestJobOne>();//Job使用瞬时依赖注入
//services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
//services.AddSingleton(provider =>
//{
// var sf = new StdSchedulerFactory();
// var scheduler = sf.GetScheduler().Result;
//// 通过实现IJobFactory实现依赖注入
// scheduler.JobFactory = provider.GetService<IJobFactory>();

// return scheduler;
//});
//注入Redis消息订阅管理器
services.AddSingleton<IRedisSubscription, RedisSubscriptionServer>();
//var servicesProvider = services.BuildServiceProvider();
//servicesProvider.CreateScope();

#endregion
#region 注释代码


//Assembly assembly = Assembly.Load(new AssemblyName("Uwl.ScheduledTask.Job"));
//Type jobType = assembly.GetType("Uwl.ScheduledTask.Job" + "." + "TestJobOne");
//IJobDetail job = new JobDetailImpl("1111","tets", jobType);
//var serviceProvider = services.BuildServiceProvider();
//var sched = serviceProvider.GetService<IScheduler>();
//sched.Start();
//IJobDetail job1 = JobBuilder.Create<TestJobOne>()
// .WithIdentity("作业名称", "作业分组")
// .Build();
//// 触发作业
//ITrigger trigger = TriggerBuilder.Create()



// .WithIdentity("触发器名称", "触发器分组")
// .WithCronSchedule("/5 * * ? * *") // 每隔五秒执行一次 这个表达式我们将在下一篇介绍
// .StartAt(DateTime.UtcNow)
// .WithPriority(1)
// .Build();
//// 将作业和触发器添加到调度器
//sched.ScheduleJob(job1, trigger);
#endregion


}
/// <summary>
/// 应用程序管道
Expand All @@ -400,11 +445,11 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
{

//在此处加入允许跨域
app.UseCors(CorsName).UseSignalR(routes =>
{
routes.MapHub<SignalRChat>("/api2/chatHub");
//app.UseCors(CorsName).UseSignalR(routes =>
//{
// routes.MapHub<SignalRChat>("/api2/chatHub");

}); ; //跨域第二种方法,使用策略,详细策略信息在ConfigureService中//loggerFactory.AddConsole();
//}); ; //跨域第二种方法,使用策略,详细策略信息在ConfigureService中//loggerFactory.AddConsole();
app.UseWebSockets();
#region Environment
//判断是否是环境变量
Expand Down Expand Up @@ -439,6 +484,11 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
c.SwaggerEndpoint($"/swagger/v1/swagger.json", "I_Sfront.Core API");
c.RoutePrefix = "";
});
app.UseSignalR(routes =>
{
routes.MapHub<SignalRChat>("/api2/chatHub");
});
#endregion
app.UseStaticFiles();// 使用静态文件
app.UseCookiePolicy();// 使用cookie
Expand Down
File renamed without changes.

0 comments on commit 22ebe09

Please sign in to comment.