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

定时任务 Wpf.Quartz.Demo.4

程序员文章站 2022-04-28 13:02:40
本文继续介绍定时任务 Wpf.Quartz.Demo.3的一些小细节, 代码也请前往第3节下载。 1.RichTextBox右键菜单

本文继续介绍定时任务 wpf.quartz.demo.3的一些小细节, 代码也请前往第3节下载。

1.richtextbox右键菜单

 <richtextbox.contextmenu>
                <contextmenu>
                    <menuitem header="剪贴" command="applicationcommands.cut"/>                     
                    <menuitem header="复制" command="applicationcommands.copy"/>                                         
                    <menuitem header="粘贴" command="applicationcommands.paste"/>                                          
                    <menuitem header="清除" click="menuitemclear_click"/>   
                    <menuitem x:name="menupause" header="暂停" click="menuitempause_click"/>   
                </contextmenu>
            </richtextbox.contextmenu>

其中上面上个是系统默认的,自己要添加,可以自己定义。

2.右键datagrid,选中该行。

 <i:interaction.triggers>
                <i:eventtrigger eventname="previewmouserightbuttondown">
                    <local:exinvokecommandaction command="{binding previewmouserightcomamnd}" commandparameter="{binding selecteditem, elementname=table}"/>
                </i:eventtrigger>
            </i:interaction.triggers>

private void previewmouseright(object para)
        {
            routedeventargs e = ((excommandparameter)para).eventargs as routedeventargs;
            var treeviewitem = visualupwardsearch<uielement>(e.originalsource as dependencyobject) as uielement;

            if (treeviewitem == null) return;
            treeviewitem.focus();
            e.handled = true;
        }

        private static dependencyobject visualupwardsearch<m>(dependencyobject source)
        {
            while (source != null && source.gettype() != typeof(m))
            {
                if (source is visual || source is visual3d)
                    source = visualtreehelper.getparent(source);
                else
                    source = logicaltreehelper.getparent(source);
            }
            return source;
        }

3.任务的基本接口,主要是系统的启动,停止等命令

定时任务 Wpf.Quartz.Demo.4
public interface irun:ibaserunner
    {
        [newtonsoft.json.jsonignore()]
        action<string, loglevel> logout { get; set; }

        task start();

        task stop();

        task restart();

        task resume();

        task pause();

        task runnowonetime();
    }
irun

4.任务的设置的接口,主要是任务的配置保存。

定时任务 Wpf.Quartz.Demo.4
 public interface ibaserunner
    {
        string name { get; }
        string displayname { get; set; }
        string remark { get; set; }
        string cronexpression { get; set; }
        triggerstate triggerstate { get; set; }
        string settingstr { get; set; }
        datetime? nextruntime { get; }
        datetime[] nextruntimes { get; set; }
        datetime? starttime { get; set; }
        datetime? endtime { get; set; }
        bool isedit { get; set; }
        cronsecondset cronsecondset { get; set; }
        cronminuteset cronminuteset { get; set; }
        cronhourset cronhourset { get; set; }
        crondayset crondayset { get; set; }
        cronmonthset cronmonthset { get; set; }
        cronweekset cronweekset { get; set; }
        cronyearset cronyearset { get; set; }
        easycronset easycronset { get; set; }
        mode mode { get; set; }
        void info(string message);
        void debug(string message);
        void error(string message);
        void fatal(string message);
        void warn(string message);

    }
ibaserunner

5.任务类,接口irun的实现。

定时任务 Wpf.Quartz.Demo.4
using quartz;
using quartz.impl;
using quartz.spi;
using system;
using system.collections.generic;
using system.linq;
using system.reflection;
using system.text;
using system.threading;
using system.threading.tasks;
using wpf.quartz.converters;

namespace wpf.quartz
{
    public class simplerunner<t> : baserunner,irun where t : ijob
    {
        public simplerunner()
        {
            base.name = this.name;
        }

        private static readonly log4net.ilog log = log4net.logmanager.getlogger(system.reflection.methodbase.getcurrentmethod().declaringtype);
        public new string name
        {
            //get { return gettype().name; }
            get { return typeof(t).name; }
        }


        private readonly semaphoreslim locker = new semaphoreslim(1);

        public virtual async task start()
        {
            if (statusenableconverter.iseanblestate(triggerstate, "start") == false)
            {
                return;
            }
            await locker.waitasync();
            try
            {

                if (string.isnullorempty(cronexpression))//如果为空,则设置为立刻执行一次
                {
                    cronexpression = cronhelper.datetime2cron(datetime.now.addseconds(3));
                }
                info((displayname ?? name) + "开始启动!");
                triggerstate= await quartzhelper.instance.startjobexecutebycron<t>(cronexpression, name, this, this.starttime, this.endtime);
                info((displayname ?? name) + "启动完毕!");

                nextruntimes = quartzhelper.instance.getnextruntime(cronexpression, starttime, endtime, 5);
                isedit = false;
            }
            catch (exception ex)
            {
                log.fatal(ex);
                info((displayname ?? name) + "启动失败!" + ex.message);
            }
            finally
            {
                triggerstate = await quartzhelper.instance.getjobstate(name);
                locker.release();
            }
        }

        public virtual async task restart()
        {
            if (statusenableconverter.iseanblestate(triggerstate, "restart") == false)
            {
                return;
            }
            await locker.waitasync();
            try
            {
                if (string.isnullorempty(cronexpression))//如果为空,则设置为立刻执行一次
                {
                    cronexpression = cronhelper.datetime2cron(datetime.now.addseconds(3));
                }
                info(displayname??name + "开始重新启动!");
                triggerstate = await quartzhelper.instance.removejob(name);
                triggerstate = await quartzhelper.instance.startjobexecutebycron<t>(cronexpression, name, this, this.starttime, this.endtime);
                info((displayname ?? name) + "重新启动完毕!");

                nextruntimes = quartzhelper.instance.getnextruntime(cronexpression, starttime, endtime, 5);
                isedit = false;
            }
            catch (exception ex)
            {
                log.fatal(ex);
                info((displayname ?? name) + "重新启动失败!" + ex.message);
            }
            finally
            {
                triggerstate = await quartzhelper.instance.getjobstate(name);
                locker.release();
            }
        }

        public virtual async task pause()
        {
            if (statusenableconverter.iseanblestate(triggerstate, "pause") == false)
            {
                return;
            }
            try
            {
                info((displayname ?? name) + "开始暂停!");
                triggerstate = await quartzhelper.instance.pausejob(name);
                info((displayname ?? name) + "暂停完毕!");
            }
            catch (exception ex)
            {
                log.fatal(ex);
                info((displayname ?? name) + "暂停失败!" + ex.message);
            }
        }

        public virtual async task resume()
        {
            if (statusenableconverter.iseanblestate(triggerstate, "resume") == false)
            {
                return;
            }
            try
            {
                info((displayname ?? name) + "开始恢复!");
                triggerstate = await quartzhelper.instance.resumejob(name);
                info((displayname ?? name) + "恢复完毕!");
            }
            catch (exception ex)
            {
                log.fatal(ex);
                info((displayname ?? name) + "恢复失败!" + ex.message);
            }
        }

        public virtual async task stop()
        {
            if (statusenableconverter.iseanblestate(triggerstate, "stop") == false)
            {
                return;
            }
            try
            {
                info((displayname ?? name) + "开始停止!");
                triggerstate = await quartzhelper.instance.removejob(name);
                info((displayname ?? name) + "停止完毕!");               
            }
            catch (exception ex)
            {
                log.fatal(ex);
                info((displayname ?? name) + "停止失败!" + ex.message);
            }
        }

        public virtual async task runnowonetime()
        {
            if (statusenableconverter.iseanblestate(triggerstate, "run") == false)
            {
                return;
            }
            if (locker.currentcount == 0)
            {
                info((displayname ?? name) + "正在执行,请稍后再执行!");
                return;
            }
            await locker.waitasync();
            try
            {
                info((displayname ?? name) + "开始执行一次!");
                ischedulerfactory sf = new stdschedulerfactory();
                ischeduler scheduler = await sf.getscheduler();
                await scheduler.start();

                ijobdetail job = await scheduler.getjobdetail(new jobkey(name, "group1"));
                if (job == null)
                {
                    job = jobbuilder.create<hellojob>()
                   .withidentity(name, "group1")
                   .build();
                }

                itrigger trigger = await scheduler.gettrigger(new triggerkey(name, "group1"));
                if (trigger == null)
                {
                    trigger = triggerbuilder.create()
                       .withidentity(name, "group1")
                       .startnow()
                       .withsimpleschedule(x => x
                       .withintervalinseconds(1))
                       .build();
                }
              
                await scheduler.schedulejob(job, trigger);

                info((displayname ?? name) + string.format("执行一次完毕"));

                
                //await task.delay(timespan.fromseconds(5));

                //await scheduler.shutdown();              

                //schedulermetadata metadata = await scheduler.getmetadata();
                //info(string.format("执行完毕{0}个任务.", metadata.numberofjobsexecuted));

            }
            catch (exception ex)
            {
                log.fatal(ex);
                info((displayname ?? name) + string.format("执行一次失败") + ex.message);
            }
            finally
            {
                locker.release();
            }
        }
    }
}
simplerunner

6.baserunner,主要是设置cron

定时任务 Wpf.Quartz.Demo.4
using quartz;
using system;
using system.collections.generic;
using system.componentmodel;
using system.linq;
using system.text;
using system.threading.tasks;
using wpf.quartz.models;

namespace wpf.quartz
{
    public class baserunner: baselog, inotifypropertychanged
    {
        public string name { get; set;}

        private string displayname;
        public string displayname
        {
            get { return displayname; }
            set
            {
                if (displayname != value)
                {
                    displayname = value;
                    onpropertychanged("displayname");
                }
            }
        }

        private string remark;
        public string remark
        {
            get { return remark; }
            set
            {
                if (remark != value)
                {
                    remark = value;
                    onpropertychanged("remark");
                }
            }
        }

        private string cronexpression;
        public string cronexpression
        {
            get { return cronexpression; }
            set
            {
                if (cronexpression != value)
                {
                    cronexpression = value;
                    onpropertychanged("cronexpression");
                }
            }
        }

        private triggerstate triggerstate = triggerstate.none;
        public triggerstate triggerstate
        {
            get { return triggerstate; }
            set
            {
                if (triggerstate != value)
                {
                    triggerstate = value;
                    onpropertychanged("triggerstate");
                }
            }
        }

        private string settingstr = "手动执行";
        public string settingstr
        {
            get { return settingstr; }
            set
            {
                if (settingstr != value)
                {
                    settingstr = value;
                    onpropertychanged("settingstr");
                }
            }
        }

        public datetime? nextruntime
        {
            get
            {
                if (nextruntimes != null && nextruntimes.length > 0)
                {
                    return nextruntimes[0];                  
                }
                else
                {
                    return null;
                }
            }
           
        }

        private datetime[] nextruntimes;
        public datetime[] nextruntimes
        {
            get { return nextruntimes; }
            set
            {
                if (nextruntimes != value)
                {
                    nextruntimes = value;
                    onpropertychanged("nextruntimes");
                    onpropertychanged("nextruntime");
                }
            }
        }

        private datetime? starttime;
        public datetime? starttime
        {
            get { return starttime; }
            set
            {
                if (starttime != value)
                {
                    starttime = value;
                    onpropertychanged("starttime");
                }
            }
        }

        private datetime? endtime;
        public datetime? endtime
        {
            get { return endtime; }
            set
            {
                if (endtime != value)
                {
                    endtime = value;
                    onpropertychanged("endtime");
                }
            }
        }

        private bool isedit;
        public bool isedit
        {
            get { return isedit; }
            set
            {
                if (isedit != value)
                {
                    isedit = value;
                    onpropertychanged("isedit");
                }
            }
        }

        public cronsecondset cronsecondset { get; set; } = new cronsecondset();
        public cronminuteset cronminuteset { get; set; } = new cronminuteset();
        public cronhourset cronhourset { get; set; } = new cronhourset();
        public crondayset crondayset { get; set; } = new crondayset();
        public cronmonthset cronmonthset { get; set; } = new cronmonthset();
        public cronweekset cronweekset { get; set; } = new cronweekset();
        public cronyearset cronyearset { get; set; } = new cronyearset();
        public easycronset easycronset { get; set; } = new easycronset();

        private mode mode;
        public mode mode
        {
            get { return mode; }
            set
            {
                if (mode != value)
                {
                    mode = value;
                    onpropertychanged("mode");
                    cronsecondset.updateexpression();
                }
            }
        }

        private setmode setmode = setmode.easy;
        public setmode setmode
        {
            get { return setmode; }
            set
            {
                if (setmode != value)
                {
                    setmode = value;
                    onpropertychanged("setmode");
                    cronsecondset.updateexpression();
                }
            }
        }

        public event propertychangedeventhandler propertychanged;
        public void onpropertychanged(string propertyname)
        {
            if (propertychanged != null)
            {
                propertychanged(this, new propertychangedeventargs(propertyname));
            }
        }

    }

    public class baselog
    {
        #region 日志输出
        [newtonsoft.json.jsonignore()]
        public action<string, loglevel> logout { get; set; }

        public void info(string message)
        {
            if (logout != null)
            {
                app.current.dispatcher.invoke((action)delegate ()
                {
                    logout(message, loglevel.info);
                });
            }
        }

        public void debug(string message)
        {
            if (logout != null)
            {
                app.current.dispatcher.invoke((action)delegate ()
                {
                    logout(message, loglevel.debug);
                });
            }
        }

        public void error(string message)
        {
            if (logout != null)
            {
                app.current.dispatcher.invoke((action)delegate ()
                {
                    logout(message, loglevel.error);
                });
            }
        }

        public void fatal(string message)
        {
            if (logout != null)
            {
                app.current.dispatcher.invoke((action)delegate ()
                {
                    logout(message, loglevel.fatal);
                });
            }
        }

        public void warn(string message)
        {
            if (logout != null)
            {
                app.current.dispatcher.invoke((action)delegate ()
                {
                    logout(message, loglevel.warn);
                });
            }
        }
        #endregion
    }
}
baserunner

具体的请自行查看对应的类。

        public cronsecondset cronsecondset { get; set; } = new cronsecondset();
        public cronminuteset cronminuteset { get; set; } = new cronminuteset();
        public cronhourset cronhourset { get; set; } = new cronhourset();
        public crondayset crondayset { get; set; } = new crondayset();
        public cronmonthset cronmonthset { get; set; } = new cronmonthset();
        public cronweekset cronweekset { get; set; } = new cronweekset();
        public cronyearset cronyearset { get; set; } = new cronyearset();


        public easycronset easycronset { get; set; } = new easycronset();

 

主要代码就是用户自定义设置,大家运行程序看效果。

定时任务 Wpf.Quartz.Demo.4

另外,这种设置太专业了,不适合用户使用,因此设计了用户常用的模式。

定时任务 Wpf.Quartz.Demo.4

是不是简单友好多了。

至此完结。

 

下次打算写一个wcf的demo,当自己学习的动力。