带参数的Quartz.Net 使用

1、创建项目QuartzDemoWithParas

创建WinForm项目,采用.netframework4.5.2版本,在form1中添加四个按钮,一会使用创建四个任务 

2、引入Quartz.Net项目

使用nuget,添加对Quartz.Net的引用,并添加类:FirstJob,继承IJob,具体实现如下:

在3.0.7版本上Execute方法返回值是Task,与2.x版本不一样,需要注意

namespace QuartzDemoWithParas
{
    public class FirstJob : IJob
    {
        public const string JobAddress = "Address";
        public Task Execute(IJobExecutionContext context)
        {
            return Task.Factory.StartNew(() =>
            {
                //通过job 传递过来的参数
                JobDataMap data = context.JobDetail.JobDataMap;
                var jobAddress = data.GetIntValue(JobAddress);
                //获取窗体运行实例
                var instance = (Form1)Application.OpenForms["Form1"];

                Debug.WriteLine($"设备地址:{jobAddress}, 数据: {instance.Count} ,时间:{DateTime.Now}");
                instance.Count++;
            });
            
        }
    }
}

3、添加创建Job的方法

quartz.net 3.x版本上使用了很多异步方法,使用时需要注意

private async void CreateJob(int address)
{
     Debug.WriteLine($"创建任务,时间:{DateTime.Now}");
     IScheduler scheduler =await Quartz.Impl.StdSchedulerFactory.GetDefaultScheduler();
            scheduler.Start();

     IJobDetail job1 = JobBuilder.Create<FirstJob>().WithIdentity($"Address{address}", "Drip").Build();

     job1.JobDataMap.Put(FirstJob.JobAddress, address);
     ITrigger trigger1 = TriggerBuilder.Create().WithIdentity($"Address{address}", "DripTri").StartNow()
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).WithRepeatCount(10)).Build();

     scheduler.ScheduleJob(job1, trigger1);
}

4、实现各个按钮的功能

        private void button1_Click(object sender, EventArgs e)
        {
            CreateJob(1);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            CreateJob(2);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            CreateJob(3);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            CreateJob(4);
        }

5、调试运行

F5运行,并通过点击Job1按钮的运行结果

通过点击四个按钮,并同时运行部分结果

6、补充

当一个job运行过程中,如果再次点击那个运行job的相关按钮时,在2.x版本就会出现错误,但是在3.x版本上没有错误,因此加上如下代码防止出错。

        private async void button1_Click(object sender, EventArgs e)
        {
            IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();
            JobKey key = JobKey.Create($"Address1","Drip");
            var exist =  await scheduler.CheckExists(key);
            if (!exist)
            {
                CreateJob(1);
            }
            else
            {
                MessageBox.Show("当前已运行Job:1");
            }
            
        }


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值