You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
122 lines
3.6 KiB
122 lines
3.6 KiB
using Autofac;
|
|
using Autofac.Core;
|
|
using Hangfire;
|
|
using PluginSystem;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace JobSystem
|
|
{
|
|
public class DynamicJobManager
|
|
{
|
|
private readonly IComponentContext _container;
|
|
private readonly IRecurringJobManager _recurringJobManager;
|
|
|
|
public DynamicJobManager(IComponentContext container, IRecurringJobManager recurringJobManager)
|
|
{
|
|
_container = container;
|
|
_recurringJobManager = recurringJobManager;
|
|
}
|
|
|
|
// 注册所有可用的插件为定期任务
|
|
public void RegisterAllPluginJobs()
|
|
{
|
|
var pluginTypes = GetAvailablePluginTypes();
|
|
|
|
foreach (var pluginType in pluginTypes)
|
|
{
|
|
var pluginName = GetPluginName(pluginType);
|
|
var cronExpression = GetCronExpressionForPlugin(pluginType);
|
|
|
|
RegisterJob(pluginName, pluginType, cronExpression);
|
|
}
|
|
}
|
|
|
|
// 注册单个动态任务
|
|
public void RegisterJob(string jobId, Type type, string cronExpression)
|
|
{
|
|
//var pluginType = Type.GetType(pluginTypeName);
|
|
var pluginType = type;
|
|
if (pluginType == null || !typeof(IJobPlugin).IsAssignableFrom(pluginType))
|
|
{
|
|
throw new ArgumentException($"Invalid plugin type: {
|
|
|
|
pluginType.FullName
|
|
//pluginTypeName
|
|
}");
|
|
}
|
|
|
|
// 使用Hangfire注册定期任务
|
|
_recurringJobManager.AddOrUpdate(
|
|
jobId,
|
|
() => ExecutePluginJob(pluginType),
|
|
cronExpression);
|
|
}
|
|
|
|
// 执行插件任务的入口点
|
|
public async Task ExecutePluginJob(
|
|
Type pluginType
|
|
//string pluginTypeName
|
|
|
|
|
|
)
|
|
{
|
|
//var pluginType = Type.GetType(pluginTypeName);
|
|
if (pluginType == null)
|
|
{
|
|
throw new ArgumentException($"Plugin type not found: {pluginType.FullName}");
|
|
}
|
|
|
|
try
|
|
{
|
|
// 从容器中解析插件实例
|
|
var plugin = _container.Resolve(pluginType) as IJobPlugin;
|
|
if (plugin != null)
|
|
{
|
|
await plugin.ExecuteAsync();
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// 记录任务执行异常
|
|
Console.WriteLine($"Error executing plugin job: {ex.Message}");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
// 获取所有可用的插件类型
|
|
private IEnumerable<Type> GetAvailablePluginTypes()
|
|
{
|
|
return _container.ComponentRegistry.Registrations
|
|
.SelectMany(r => r.Services.OfType<TypedService>())
|
|
.Select(s => s.ServiceType)
|
|
.Where(t => typeof(IJobPlugin).IsAssignableFrom(t)
|
|
&& !t.IsAbstract
|
|
|
|
);
|
|
}
|
|
|
|
// 获取插件名称(可以从特性或类型名派生)
|
|
private string GetPluginName(Type pluginType)
|
|
{
|
|
return pluginType.Name.Replace("Job", "");
|
|
}
|
|
|
|
// 获取插件的Cron表达式(可以从配置或特性获取)
|
|
private string GetCronExpressionForPlugin(Type pluginType)
|
|
{
|
|
// 默认每小时执行一次,实际应用中可以从配置读取
|
|
return Cron.Minutely();
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|