欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

定时任务 Wpf.Quartz.Demo.1

程序员文章站 2022-04-08 20:29:55
Quartz 是个开源的作业调度框架. 安装:Install-Package Quartz 官网文档地址:https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/using-quartz.html 资源比较多,这里不做介绍 ......

 quartz 是个开源的作业调度框架.

安装:install-package quartz

官网文档地址:

资源比较多,这里不做介绍。

任务设置有两种方式:simpletrigger和crontrigger,如下:

var trigger = (isimpletrigger) triggerbuilder.create()
    .withidentity("trigger1", "group1")
    .startat(mystarttime) // some date
    .forjob("job1", "group1") // identify job with name, group strings

 var trigger = triggerbuilder.create()

    .withidentity("trigger3", "group1")
    .withcronschedule("0 0/2 8-17 * * ?")
    .forjob("myjob", "group1")
    .build();

第二种的在线表达式生成工具网址:

在这里写个控制台的demo来看看定时任务的效果,我们先简单的封装一下任务的启动和停止等,主要代码如下: 

定时任务 Wpf.Quartz.Demo.1
  public class quartzhelper
    {
        private static quartzhelper instance = new quartzhelper();

        public static quartzhelper instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new quartzhelper();
                }
                return instance;
            }
        }

        private const string job_group_name = "job_group_name";
        private const string trigger_group_name = "trigger_group_name";

        /// <summary>
        /// 程序调度
        /// </summary>
        private static ischeduler _scheduler;

        /// <summary>
        /// 初始化任务调度对象
        /// </summary>
        private quartzhelper()
        {

        }


        /// <summary>
        /// 时间间隔执行任务
        /// </summary>
        /// <typeparam name="t">任务类,必须实现ijob接口</typeparam>
        /// <param name="seconds">时间间隔(单位:毫秒)</param>
        public async task startjobexecuteinterval<t>(int seconds, string jobname = null, string jobgroupname = null, string triggername = null, string triggergroupname = null) where t : ijob
        {
            await initjobs();

            //ijobdetail job = jobbuilder.create<t>().withidentity("job1", "group1").build();
            ijobdetail job = jobbuilder.create<t>().build();

            itrigger trigger = triggerbuilder.create()
                .startnow()
                .withsimpleschedule(x => x.withintervalinseconds(seconds).repeatforever())
                .build();

            await _scheduler.schedulejob(job, trigger);

            await _scheduler.start();
        }

        /// <summary>
        /// 指定时间执行任务
        /// </summary>
        /// <typeparam name="t">任务类,必须实现ijob接口</typeparam>
        /// <param name="cronexpression">cron表达式,即指定时间点的表达式</param>
        public async task<triggerstate> startjobexecutebycron<t>(string cronexpression, string jobname, object para = null, datetime? starttime = null, datetime? endtime = null, string jobgroupname = job_group_name, string triggername = null, string triggergroupname = trigger_group_name) where t : ijob
        {
            await initjobs();

            ijobdetail job = jobbuilder.create<t>()
                    .withidentity(jobname, jobgroupname)
                    .build();
            job.jobdatamap.put("runner", para);


            itrigger trigger;
            if (starttime == null && endtime == null)
            {
                trigger = triggerbuilder.create()
                   .withidentity(triggername ?? jobname, triggergroupname)
                   .withcronschedule(cronexpression)
                   .build();
            }
            else if (starttime != null && endtime == null)
            {
                trigger = triggerbuilder.create()
                   .withidentity(triggername ?? jobname, triggergroupname)
                   .startat(cronhelper.datetime2datetimeoffset(starttime.value))
                   .withcronschedule(cronexpression)
                   .build();
            }
            else if (starttime == null && endtime != null)
            {
                trigger = triggerbuilder.create()
                   .withidentity(triggername ?? jobname, triggergroupname)
                   .endat(cronhelper.datetime2datetimeoffset(endtime.value))
                   .withcronschedule(cronexpression)
                   .build();
            }
            else
            {
                trigger = triggerbuilder.create()
                  .withidentity(triggername ?? jobname, triggergroupname)
                  .startat(cronhelper.datetime2datetimeoffset(starttime.value))
                  .endat(cronhelper.datetime2datetimeoffset(endtime.value))
                  .withcronschedule(cronexpression)
                  .build();
            }


            await _scheduler.schedulejob(job, trigger);

            await _scheduler.start();

            return await _scheduler.gettriggerstate(trigger.key);
        }

        public async task<triggerstate> modifyjobtime(string cronexpression, string jobname, string jobgroupname = job_group_name, string triggername = null, string triggergroupname = trigger_group_name)
        {
            ijobdetail job;
            itrigger trigger;

            job = await _scheduler.getjobdetail(new jobkey(jobname, jobgroupname));
            trigger = await _scheduler.gettrigger(new triggerkey(triggername ?? jobname, triggergroupname));
            if (job == null || trigger == null)
            {
                return triggerstate.none;
            }

            await _scheduler.unschedulejob(trigger.key);

            trigger = triggerbuilder.create()
             .withidentity(trigger.key.name, trigger.key.group)
            .withcronschedule(cronexpression)
            .build();

            await _scheduler.schedulejob(job, trigger);

            return await _scheduler.gettriggerstate(trigger.key);
        }

        public async task<triggerstate> removejob(string jobname, string jobgroupname = job_group_name, string triggername = null, string triggergroupname = trigger_group_name)
        {

            ijobdetail job;
            itrigger trigger;

            job = await _scheduler.getjobdetail(new jobkey(jobname, jobgroupname));
            trigger = await _scheduler.gettrigger(new triggerkey(triggername ?? jobname, triggergroupname));
            if (job == null || trigger == null)
            {
                return triggerstate.none;
            }

            await _scheduler.unschedulejob(trigger.key);
            await _scheduler.deletejob(job.key);

            return await _scheduler.gettriggerstate(trigger.key);
        }

        public async task<triggerstate> pausejob(string jobname, string jobgroupname = job_group_name, string triggername = null, string triggergroupname = trigger_group_name)
        {
            ijobdetail job;
            itrigger trigger;

            job = await _scheduler.getjobdetail(new jobkey(jobname, jobgroupname));
            trigger = await _scheduler.gettrigger(new triggerkey(triggername ?? jobname, triggergroupname));
            if (job == null || trigger == null)
            {
                return triggerstate.none;
            }

            await _scheduler.pausejob(job.key);

            return await _scheduler.gettriggerstate(trigger.key);
        }

        public async task<triggerstate> resumejob(string jobname, string jobgroupname = job_group_name, string triggername = null, string triggergroupname = trigger_group_name)
        {
            ijobdetail job;
            itrigger trigger;

            job = await _scheduler.getjobdetail(new jobkey(jobname, jobgroupname));
            trigger = await _scheduler.gettrigger(new triggerkey(triggername ?? jobname, triggergroupname));
            if (job == null || trigger == null)
            {
                return triggerstate.none;
            }

            await _scheduler.resumejob(job.key);

            return await _scheduler.gettriggerstate(trigger.key);
        }

        public async task<triggerstate> getjobstate(string jobname, string jobgroupname = job_group_name, string triggername = null, string triggergroupname = trigger_group_name)
        {
            ijobdetail job;
            itrigger trigger;

            job = await _scheduler.getjobdetail(new jobkey(jobname, jobgroupname));
            trigger = await _scheduler.gettrigger(new triggerkey(triggername ?? jobname, triggergroupname));
            if (job == null || trigger == null)
            {
                return triggerstate.none;
            }
            return await _scheduler.gettriggerstate(trigger.key);
        }

        public async task initjobs()
        {
            if (_scheduler != null)
            {
                return;
            }

            //配置文件的方式,配置quartz实例
            ischedulerfactory schedulerfactory = new stdschedulerfactory();
            _scheduler = await schedulerfactory.getscheduler();
        }

        public async task startjobs()
        {
            if (_scheduler != null)
            {
                await _scheduler.start(); return;
            }

            //配置文件的方式,配置quartz实例
            ischedulerfactory schedulerfactory = new stdschedulerfactory();
            _scheduler = await schedulerfactory.getscheduler();
            await _scheduler.start();
        }

        public void standbyjobs()
        {
            try
            {
                if (_scheduler == null) return;
                if (!_scheduler.instandbymode)
                {
                    _scheduler.standby();
                }
            }
            catch (exception ex)
            {
                throw new exception(ex.message);
            }
        }

        public void restartjobs()
        {
            _scheduler.shutdown();
            _scheduler.start();
        }

        public datetime[] getnextruntime(string cronexpression, datetime? starttime,datetime? endtime, int number = 1)
        {
            try
            {
                itrigger trigger = null;
                if (starttime == null && endtime == null)
                {
                    trigger = triggerbuilder.create()
                        .withcronschedule(cronexpression)
                        .build();
                }
                else if (starttime != null && endtime == null)
                {
                    trigger = triggerbuilder.create()
                       .startat(cronhelper.datetime2datetimeoffset(starttime.value))
                       .withcronschedule(cronexpression)
                       .build();
                }
                else if (starttime == null && endtime != null)
                {
                    trigger = triggerbuilder.create()
                       .endat(cronhelper.datetime2datetimeoffset(endtime.value))
                       .withcronschedule(cronexpression)
                       .build();
                }
                else
                {
                    trigger = triggerbuilder.create()
                      .startat(cronhelper.datetime2datetimeoffset(starttime.value))
                      .endat(cronhelper.datetime2datetimeoffset(endtime.value))
                      .withcronschedule(cronexpression)
                      .build();
                }

               
                ilist<datetimeoffset> dates = triggerutils.computefiretimes(trigger as ioperabletrigger, null, number).tolist();
                if (dates != null && dates.count > 0)
                {
                    return dates.select(p => timezoneinfo.converttimefromutc(p.datetime, timezoneinfo.local)).toarray();
                }
            }
            catch (exception ex)
            {

            }
            return null;
        }
    }
view code

 执行一个每5s执行一次的例子如下:

var triggerstate = await quartzhelper.instance.startjobexecutebycron<hellojob>("0/5 * * * * ?", "测试1");

  

 代码下载地址如下:https://pan.baidu.com/s/1w1uwofpgyfo_etdpheegsg