首先需要再 Global文件中,创建调度器,哎呀,直接上代码吧
public class MvcApplication : System.Web.HttpApplication
{
private static IScheduler _scheduler;
private ScheduleJobsManager _jobMana;
protected void Application_Start()
{
var factory = new StdSchedulerFactory();
_scheduler = factory.GetScheduler();
_scheduler.Start();
_jobMana = new ScheduleJobsManager(_scheduler);
RegisterJobs();
}
//在网站启动的时候,将数据库中正在运行状态的任务,启动起来
private void RegisterJobs()
{
var list = _jobMana.GetList(s => s.JobStatus == "Running");
foreach (var job in list)
{
_jobMana.AddJob(job);
}
}
//这个方法,是在其他地方使用的,相当于 单例模式,全局只有这一个调度器
public static IScheduler GetScheduler()
{
return _scheduler;
}
}
接下来说下,管理任务调度的控制器和界面
控制器这样写:
private IScheduler _scheduler = MvcApplication.GetScheduler();//这个就是Global中的那个静态方法
private ScheduleJobsManager _scheduleJobsManager; //这个是对任务调度的一个封装,也是操作数据的操作类,后面会给代码
private JobLogsManager _jobLog = new JobLogsManager(); //这个是与数据库对用的Job日志操作类
//初始化控制器,需要给调度管理进行初始化
public JobController()
{
_scheduleJobsManager = new ScheduleJobsManager(_scheduler);
}
public ActionResult Add(ScheduleJobs job)
{
job.JobStatus = "Running";
job.CreateTime = DateTime.Now;
_scheduleJobsManager.Insert(job);
_scheduleJobsManager.AddJob(job);
return Json(new { code = 0, msg = "添加成功" });
}
public ActionResult Pause(int id)
{
try
{
if( _scheduleJobsManager.PauseJob(id))
{
return Json(new { code = 0, msg = "暂停成功" });
}
else
{
return Json(new { code = 500, msg = "暂停失败" });
}
}
catch (Exception ex)
{
return Json(new { code = 500, msg = "暂停失败:" + ex.Message });
}
}
[HttpPost]
public ActionResult Resume(int id)
{
try
{
if(_scheduleJobsManager.ResumeJob(id))
{
return Json(new { code = 0, msg = "恢复成功" });
}
return Json(new { code = 500, msg = "恢复失败" });
}
catch (Exception ex)
{
return Json(new { code = 500, msg = "恢复失败:" + ex.Message });
}
}
[HttpPost]
public ActionResult Delete(int Id)
{
var info = _scheduleJobsManager.GetById(Id);
if (_scheduleJobsManager.Delete(s => s.Id == Id))
{
_scheduleJobsManager.DeleteJob(info);
return Json(new { code = 0, msg = "删除成功" });
}
else
{
return Json(new { code = -1, msg = "删除失败" });
}
}
[HttpPost]
public ActionResult Edit(ScheduleJobs job)
{
var existingJob =_scheduleJobsManager.GetById(job.Id);
if (existingJob == null)
throw new Exception("任务不存在");
try
{
// 删除旧的任务
_scheduler.DeleteJob(new JobKey(existingJob.JobName, existingJob.JobGroup));
// 创建新的任务
_scheduleJobsManager.AddJob(job);
existingJob.JobName = job.JobName;
existingJob.JobGroup = job.JobGroup;
existingJob.JobClassName = job.JobClassName;
existingJob.AssemblyName = job.AssemblyName;
existingJob.CronExpression = job.CronExpression;
existingJob.Description = job.Description;
_scheduleJobsManager.Update(existingJob);
return Json(new { code = 0, msg = "更新成功" });
}
catch (Exception ex)
{
return Json(new { code = 500, msg = "更新失败:" + ex.Message });
}
}
ScheduleJobsManager.cs
public class ScheduleJobsManager : DbContext<ScheduleJobs>
{
//当前类已经继承了 DbContext增、删、查、改的方法
private readonly IScheduler _scheduler ;
public ScheduleJobsManager(IScheduler scheduler) {
_scheduler = scheduler ;
}
public void RunJobOnce(int id)
{
var job = GetById(id);
if (job == null)
throw new Exception("任务不存在");
var jobKey = new JobKey(job.JobName, job.JobGroup);
_scheduler.TriggerJob(jobKey);
}
private IJobDetail CreateJobDetail(ScheduleJobs jobInfo)
{
// 获取任务类型
Type jobType;
if (string.IsNullOrEmpty(jobInfo.AssemblyName))
{
// 从当前程序集获取类型
jobType = Type.GetType(jobInfo.JobClassName);
}
else
{
// 从指定程序集加载类型
var assembly = Assembly.Load(jobInfo.AssemblyName);
jobType = assembly.GetType(jobInfo.JobClassName);
}
if (jobType == null)
{
throw new Exception($"找不到任务类型:{jobInfo.JobClassName}");
}
// 验证类型是否实现IJob接口
if (!typeof(IJob).IsAssignableFrom(jobType))
{
throw new Exception($"任务类型 {jobInfo.JobClassName} 必须实现IJob接口");
}
// 创建任务详情
return JobBuilder.Create(jobType)
.WithIdentity(jobInfo.JobName, jobInfo.JobGroup)
.WithDescription(jobInfo.Description)
.UsingJobData("jobId", jobInfo.Id) // 传递任务ID
.Build();
}
public void AddJob(ScheduleJobs job)
{
try
{
// 创建任务
var jobDetail = CreateJobDetail(job);
var trigger = TriggerBuilder.Create()
.WithIdentity($"{job.JobName}_trigger", job.JobGroup)
.WithCronSchedule(job.CronExpression)
.Build();
// 添加到调度器
_scheduler.ScheduleJob(jobDetail, trigger);
}
catch (Exception ex)
{
throw new Exception($"添加任务失败: {ex.Message}", ex);
}
}
public bool PauseJob(int id)
{
var job = GetById(id);
_scheduler.PauseJob(new JobKey(job.JobName, job.JobGroup));
job.JobStatus = "Paused";
return Update(job);
}
public bool ResumeJob(int id)
{
var job = GetById(id);
_scheduler.ResumeJob(new JobKey(job.JobName, job.JobGroup));
job.JobStatus = "Running";
return Update(job);
}
public void DeleteJob(ScheduleJobs job)
{
_scheduler.DeleteJob(new JobKey(job.JobName, job.JobGroup));
}
}
View界面就是简单的添加修改删除,用的layui框架做的,这个就做代码了,自己用自己的框架做吧