当前位置: 首页 > article >正文

Asp.net 如何使用任务调度

首先需要再 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框架做的,这个就做代码了,自己用自己的框架做吧


http://www.kler.cn/a/505380.html

相关文章:

  • 《C++11》深入剖析正则表达式库:解锁文本处理的高效之道
  • 晨辉面试抽签和评分管理系统之十:如何搭建自己的数据库服务器,使用本软件的网络版
  • Pytorch基础教程:从零实现手写数字分类
  • mysql-5.7.18保姆级详细安装教程
  • 自建RustDesk服务器
  • 【Rust自学】12.2. 读取文件
  • Elasticsearch搜索引擎(二)
  • 数据结构《MapSet哈希表》
  • 68_Redis数据结构-QuickList
  • 【make】makefile 函数全解
  • 迅为RK3568开发板篇OpenHarmony配置HDF驱动控制LED-新增 topeet子系统-编写 bundle.json文件
  • 初学stm32 --- SPI驱动25Q128 NOR Flash
  • day08_Kafka
  • C++实现设计模式---状态模式 (State)
  • MySQL程序之:指定程序选项
  • Kotlin 协程基础十 —— 协作、互斥锁与共享变量
  • python 爬虫学习
  • 学习第六十八行
  • 稳定144帧!云游戏体验,ToDesk搭载独立满血显卡
  • MyBatis-XML映射配置
  • Vue.js组件开发-如何实现路由懒加载
  • 代码随想录算法【Day21】
  • 【C++】B2112 石头剪子布
  • OpenStack 网络服务的插件架构
  • 诡异的Spring @RequestBody驼峰命名字段映射失败为null问题记录
  • Android Studio 警告信息:Use start instead of left to ensure...