Skip to content

Commit

Permalink
增加job启停处理
Browse files Browse the repository at this point in the history
  • Loading branch information
ÂëÉñ committed Apr 24, 2020
1 parent 3f087aa commit 74333cf
Show file tree
Hide file tree
Showing 8 changed files with 192 additions and 31 deletions.
3 changes: 3 additions & 0 deletions OpenAuth.App/AutofacExt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using System.Reflection;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.Quartz;
using Infrastructure.Cache;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -63,6 +64,8 @@ public static IContainer InitAutofac(IServiceCollection services)
{
services.AddScoped(typeof(IHttpContextAccessor), typeof(HttpContextAccessor));
}

builder.RegisterModule(new QuartzAutofacFactoryModule());

builder.Populate(services);

Expand Down
25 changes: 25 additions & 0 deletions OpenAuth.App/Jobs/SysLogJob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System.Threading.Tasks;
using OpenAuth.Repository.Domain;
using Quartz;

namespace OpenAuth.App.Jobs
{
public class SysLogJob : IJob
{
private SysLogApp _sysLogApp;

public SysLogJob(SysLogApp sysLogApp)
{
_sysLogApp = sysLogApp;
}

public Task Execute(IJobExecutionContext context)
{
_sysLogApp.Add(new SysLog
{
Content = "这是一个定时任务"
});
return Task.CompletedTask;
}
}
}
2 changes: 2 additions & 0 deletions OpenAuth.App/OpenAuth.App.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<ItemGroup>
<PackageReference Include="Autofac" Version="5.1.2" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Autofac.Extras.Quartz" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.2" />
Expand All @@ -25,6 +26,7 @@
<PackageReference Include="Moq" Version="4.13.1" />
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.0" />
<PackageReference Include="Quartz" Version="3.0.7" />
</ItemGroup>

<ItemGroup>
Expand Down
71 changes: 61 additions & 10 deletions OpenAuth.App/OpenJobApp.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using Infrastructure;
using OpenAuth.App.Interface;
using OpenAuth.App.Jobs;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Interface;
using Quartz;


namespace OpenAuth.App
{
public class OpenJobApp : BaseApp<OpenJob>
{
private RevelanceManagerApp _revelanceApp;
private SysLogApp _sysLogApp;
private IScheduler _scheduler;

/// <summary>
/// 加载列表
Expand Down Expand Up @@ -44,17 +48,12 @@ public void Add(AddOrUpdateOpenJobReq req)
Repository.Add(obj);
}

public void Update(AddOrUpdateOpenJobReq obj)
public void Update(AddOrUpdateOpenJobReq obj)
{
var user = _auth.GetCurrentUser().User;
UnitWork.Update<OpenJob>(u => u.Id == obj.Id, u => new OpenJob
{
JobName = obj.JobName,
RunCount = obj.RunCount,
ErrorCount = obj.ErrorCount,
NextRunTime = obj.NextRunTime,
LastRunTime = obj.LastRunTime,
LastErrorTime = obj.LastErrorTime,
JobType = obj.JobType,
JobCall = obj.JobCall,
JobCallParams = obj.JobCallParams,
Expand All @@ -66,14 +65,66 @@ public void Update(AddOrUpdateOpenJobReq obj)
UpdateUserName = user.Name
//todo:补充或调整自己需要的字段
});
}

#region 定时任务运行相关操作

/// <summary>
/// 返回系统的job接口
/// </summary>
/// <returns></returns>
public List<string> QueryLocalHandlers()
{
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces()
.Contains(typeof(IJob))))
.ToArray();
return types.Select(u => u.FullName).ToList();
}

public void ChangeJobStatus(ChangeJobStatusReq req)
{
var job = Repository.FindSingle(u => u.Id == req.Id);
if (job == null)
{
throw new Exception("任务不存在");
}

if (req.Status == 0) //停止
{

}
else //启动
{
_scheduler.Start();
IJobDetail jobDetail = JobBuilder.Create<SysLogJob>().WithIdentity(job.Id).Build();
ITrigger trigger = TriggerBuilder.Create()
.WithCronSchedule(job.Cron)
.WithIdentity(job.Id)
.Build();
_scheduler.ScheduleJob(jobDetail, trigger);
}


var user = _auth.GetCurrentUser().User;

job.Status = req.Status;
job.UpdateTime = DateTime.Now;
job.UpdateUserId = user.Id;
job.UpdateUserName = user.Name;
Repository.Update(job);
}

#endregion


public OpenJobApp(IUnitWork unitWork, IRepository<OpenJob> repository,
RevelanceManagerApp app, IAuth auth) : base(unitWork, repository,auth)
IAuth auth, SysLogApp sysLogApp, IScheduler scheduler) : base(unitWork, repository, auth)
{
_revelanceApp = app;
_sysLogApp = sysLogApp;
_scheduler = scheduler;
}


}
}
20 changes: 0 additions & 20 deletions OpenAuth.App/Request/AddOrUpdateOpenJobReq.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,26 +32,6 @@ public partial class AddOrUpdateOpenJobReq
/// </summary>
public string JobName { get; set; }
/// <summary>
/// 任务执行次数
/// </summary>
public int RunCount { get; set; }
/// <summary>
/// 异常次数
/// </summary>
public int ErrorCount { get; set; }
/// <summary>
/// 下次执行时间
/// </summary>
public System.DateTime? NextRunTime { get; set; }
/// <summary>
/// 最后一次执行时间
/// </summary>
public System.DateTime? LastRunTime { get; set; }
/// <summary>
/// 最后一次失败时间
/// </summary>
public System.DateTime? LastErrorTime { get; set; }
/// <summary>
/// 任务执行方式0:本地任务;1:外部接口任务
/// </summary>
public int JobType { get; set; }
Expand Down
16 changes: 16 additions & 0 deletions OpenAuth.App/Request/ChangeJobStatusReq.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace OpenAuth.App.Request
{
public class ChangeJobStatusReq
{
/// <summary>
/// 任务ID
/// </summary>
public string Id { get; set; }

/// <summary>
/// 改变任务状态
/// 0:停止;1:启动(任务变成正在运行)
/// </summary>
public int Status { get; set; }
}
}
41 changes: 41 additions & 0 deletions OpenAuth.App/Test/TestJob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using Infrastructure;
using Infrastructure.Cache;
using Microsoft.AspNetCore.Http;
using NUnit.Framework;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using OpenAuth.App.Request;
using OpenAuth.App.SSO;

namespace OpenAuth.App.Test
{
[TestFixture]
public class TestJob :TestBase
{
public override ServiceCollection GetService()
{
var services = new ServiceCollection();

var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = "admin" });
services.AddScoped(x => cachemock.Object);

var httpContextAccessorMock = new Mock<IHttpContextAccessor>();
httpContextAccessorMock.Setup(x => x.HttpContext.Request.Query[Define.TOKEN_NAME]).Returns("tokentest");

services.AddScoped(x => httpContextAccessorMock.Object);

return services;
}


[Test]
public void GetSysJobs()
{
var app = _autofacServiceProvider.GetService<OpenJobApp>();
var result = app.QueryLocalHandlers();
Console.WriteLine(JsonHelper.Instance.Serialize(result));
}
}
}
45 changes: 44 additions & 1 deletion OpenAuth.WebApi/Controllers/OpenJobsController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using Infrastructure;
using System.Collections.Generic;
using Infrastructure;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App;
using OpenAuth.App.Request;
Expand Down Expand Up @@ -111,6 +112,48 @@ public Response Delete([FromBody]string[] ids)

return result;
}

/// <summary>
/// 获取本地可执行的任务列表
/// </summary>
[HttpPost]
public Response<List<string>> QueryLocalHandlers()
{
var result = new Response<List<string>>();
try
{
result.Result = _app.QueryLocalHandlers();
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.InnerException?.Message ?? ex.Message;
}

return result;
}

/// <summary>
/// 改变任务状态,启动/停止
/// </summary>
[HttpPost]
public Response ChangeStatus(ChangeJobStatusReq req)
{
var result = new Response();
try
{
_app.ChangeJobStatus(req);

}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.InnerException?.Message ?? ex.Message;
}

return result;
}


public OpenJobsController(OpenJobApp app)
{
Expand Down

0 comments on commit 74333cf

Please sign in to comment.