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

C# Quartzs定时器的使用教程

程序员文章站 2022-03-13 09:58:30
目录前言实现步骤前言首先想到倒计时,定时任务。大家想到的肯定就是定时器。那么定时器在web和winfrom程序中有着很大的作用。那在服务器端有没有像定时器一样的存在呢。有了这些需求,我找到了第三方的组...

前言

首先想到倒计时,定时任务。大家想到的肯定就是定时器。那么定时器在web和winfrom程序中有着很大的作用。那在服务器端有没有像定时器一样的存在呢。

有了这些需求,我找到了第三方的组件 quartz.net 来实现(源码位置

实现步骤

(1)第一步,通过nuget下载quartz.net组件并且引用到当前工程中

C# Quartzs定时器的使用教程

(2)创建两个类,一个是操作类,一个类继承ijob 并且需要实现ijob的方法。 

/// <summary>
    /// 操作类
    /// </summary>
    public class operation : basebusiness<auction>
    {

        #region 实例化

        public operation()
        {
            _options = new options();
        }

        internal ioptions _options { get; }

        #endregion

        public static ischeduler scheduler;
        public static ischedulerfactory factory;
        /// <summary>
        /// 获取cron表达式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns></returns>
        public string getcron(datetime? time)
        {
            var txt = convert.todatetime(time).tostring("yyyy-mm-dd-hh-mm-ss");
            var arr = txt.split('-');
            var result = string.format("{0} {1} {2} {3} {4} ? {5}", arr[5], arr[4], arr[3], arr[2], arr[1], arr[0]);
            return result;
        }
        /// <summary>
        /// 删除job
        /// </summary>
        /// <param name="id">拍卖数据对象主键</param>
        /// <param name="groupname">job的组名</param>
        public void removejob(string id, string markgoodsid, string groupname)
        {
            //var jobkey = new jobkey(groupname + id + mid + "j", groupname);
            var job = new jobkey(groupname + id + markgoodsid + "j", groupname);
            scheduler.deletejob(job);
        }


        //清楚所有定时任务
        public void clearjob()
        {
            if (scheduler != null)
            {
                scheduler.clear();

            }
        }


    }
public class setauctionings : operation, ijob
    {
        public async task execute(ijobexecutioncontext context)
        {
            await task.run(() =>
            {

                datetime freetime = context.jobdetail.jobdatamap.getdatetime("freetime");
                var now = datetime.now;

                //记录两个时间的差
                var days = freetime.subtract(now).days;
                var hours = freetime.subtract(now).hours;
                var minutes = freetime.subtract(now).minutes;
                var seconds = freetime.subtract(now).seconds;
                var result = days + "天" + hours + "时" + minutes + "分" + seconds + "秒";
//推送倒计时
                pushhelper.auctioncountdown(markid, days, hours, minutes, seconds);





                //gettriggerstate


            });
        }


/// <summary>
        /// 设置定时任务
        /// </summary>
        /// <param name="id">标的id</param>
        public void addqz(datetime begintime, datetime freetime)
        {

            var groupname = _options.getpkbyid<options_auctionstate>("1316283839361847296").tostring();
            factory = new stdschedulerfactory();
            scheduler = factory.getscheduler().result;
            var jobkey = new jobkey(groupname + id + mid + "j", groupname);
            var gjobdetail = scheduler.getjobdetail(jobkey);
            if (gjobdetail != null)
            {
                //删除任务
                scheduler.deletejob(jobkey);
            }


            //设置job  statefuljob 
            var job = jobbuilder.create<setauctionings>()
                       .withidentity(groupname + id + mid + "j", groupname)
                       .build();



            job.jobdatamap.put("freetime", freetime);
//【方法1】 设置每秒执行
            itrigger trigger = triggerbuilder.create()
                .withidentity(groupname + id + mid + "t", groupname)
                .withsimpleschedule(x => x.withintervalinseconds(1)
                .repeatforever())
                .startat(new datetimeoffset(begintime))
                .endat(new datetimeoffset(freetime))
                .build();


            //【方法2】
            //var execss = "0/1 * * * * ?";
            //itrigger trigger = triggerbuilder.create()
            //    .withidentity(groupname + id + meetingplace + "t", groupname)
            //    .withcronschedule(execss)
            //    .startat(new datetimeoffset(begintime))
            //    .endat(new datetimeoffset(freetime))
            //    .build();

            scheduler.schedulejob(job, trigger);
        }

    }

以上是一个简单的封装,可以根据这个倒计时的推送。增加一些封装 如:暂停,恢复,结束,更新等。

调用的话只需要简单的实例化一下进行调用。

然后我在大概说下其他封装的思路和代码片段;

延时倒计时:

根据传过来的参数时间进行一个修改,删除之前的任务重新开始一个任务;

/// <summary>
        /// 【拍卖延时】修改倒计时任务
        /// </summary>
        /// <param name="id"></param>
        /// <param name="meetingplace"></param>
        /// <param name="freetime"></param>
        public void updateqz(string id, string mid, datetime freetime, datetime limittime)
        {
 
 
            //scheduler = factory.getscheduler().result;
            //if (scheduler == null)
            //    return;
 
            //拍卖进行中
            var groupname = _options.getpkbyid<options_auctionstate>("1316283839361847296").tostring();
            var jobkey = new jobkey(groupname + id + mid + "j", groupname);
            var gjobdetail = scheduler.getjobdetail(jobkey);
            if (gjobdetail.result == null)
                return;
 
 
            var triggerkey = new triggerkey(groupname + id + mid + "t", groupname);
            var triggerr = scheduler.gettrigger(triggerkey);
            var triggerbuilder = triggerr.result.gettriggerbuilder();
            //修改结束时间 withcronschedule(execss).
            itrigger newtrigger = triggerbuilder.endat(new datetimeoffset(freetime)).build();
 
 
 
            var job = gjobdetail.result;
            job.jobdatamap.put("auctionid", id);
            job.jobdatamap.put("markid", mid);
            job.jobdatamap.put("freetime", freetime);
            job.jobdatamap.put("limittime", limittime);
 
 
            //删除任务
            scheduler.deletejob(jobkey);
            scheduler.schedulejob(job, newtrigger);
 
 
            //修改最终结束的定时任务;
            setauctioneds setauctioneds = new setauctioneds();
            setauctioneds.setendqz(id, freetime, mid);
        }

倒计时暂停:

调用组件的pausetrigger方法可以进行暂停;

/// <summary>
/// 倒计时暂停
/// </summary>
public ajaxresult stopqz(string id, string mid)
{
    try
    {
 
 
 
        //方法1
        //拍卖进行中
        var groupname = _options.getpkbyid<options_auctionstate>("1316283839361847296").tostring();
 
 
 
        var mark = service.getiqueryable<markgoods>().firstordefault(x => x.id == mid);
        if (mark == null)
            return error("找不到标的!");
 
 
        //获取实际结束时间。
        var subendtime = mark.endtime.value;
        //计算暂停后剩余的时间  = audendtime(结束时间) - 当前时间
        var nowendtime = datetime.now;
        var differtime = subendtime.subtract(nowendtime);
 
        //追加 剩余时间 和 当前结束时间;
        mark.surplustime = differtime.tostring();
        //mark.endtime = nowendtime;
 
 
 
 
        //groupname + id + mid + "t", groupname
        var trikey = new triggerkey(groupname + id + mid + "t", groupname);
 
 
        var result = scheduler.gettriggerstate(trikey).result;
        if (result == triggerstate.none)
        {
            return error("失败:不存在此任务!");
        }
 
 
        if (result == triggerstate.paused)//暂停
        {
            return success("失败:该任务已暂停!");
 
        }
        else
        {
            scheduler.pausetrigger(trikey);
            mark.auctimestatus = 2;
            service.updateany<markgoods>(mark, new list<string> { "surplustime", "auctimestatus" });
            return success("成功:任务已暂停");
        }
 
 
 
 
        //方法2
        //var mark = service.getiqueryable<markgoods>().firstordefault(x => x.id == mid);
        //if (mark == null)
        //    return;
 
 
        ////获取实际结束时间。
        //var subendtime = mark.endtime.value;
        ////计算暂停后剩余的时间  = audendtime(结束时间) - 当前时间
        //var nowendtime = datetime.now;
        //var differtime = subendtime.subtract(nowendtime);
 
        ////追加 剩余时间 和 当前结束时间;
        //mark.surplustime = differtime.tostring();
        ////mark.endtime = nowendtime;
        //service.updateany<markgoods>(mark, new list<string> { "surplustime" });
 
 
 
        ////拍卖进行中
        //var groupname = _options.getpkbyid<options_auctionstate>("1316283839361847296").tostring();
        ////关闭该定时器
        //removejob(mark.auctionid, mark.id, groupname);
 
    }
    catch (exception)
    {
 
        throw;
    }
 
 
}

倒计时恢复:

俗话说得好破镜难圆,泼出去的水很难收回来。恢复也是这个道理,比如:倒计时走到了7暂停,那么恢复的时候如何从7继续呢。这里就牵扯到了时间戳并且存入数据库的介入了。

/// <summary>
        /// 恢复倒计时
        /// </summary>
        public ajaxresult returnqz(string id, string mid)
        {
            try
            {


                var mark = service.getiqueryable<markgoods>().firstordefault(x => x.id == mid);
                if (mark == null)
                    return error();
                //获取实际结束时间。
                if (mark.surplustime.isnullorempty())
                {
                    return error();
                }
                timespan.tryparse(mark.surplustime, out timespan surplustime);
                //方法1
                //拍卖进行中
                //拍卖进行中
                var groupname = _options.getpkbyid<options_auctionstate>("1316283839361847296").tostring();
                var trikey = new triggerkey(groupname + id + mid + "t", groupname);

                var result = scheduler.gettriggerstate(trikey).result;
                if (result == triggerstate.none)
                {
                    return error("失败:不存在此任务!");
                }
                if (result == triggerstate.normal)//暂停
                {
                    return error("失败:任务正在进行,无需恢复!");

                }
                else
                {

                    //结束时间  = 当前时间 + 剩余时间
                    var endtime = datetime.now.add(surplustime);
                    //获取限时竞价时间
                    var limittime = endtime.addhours(-mark.limithh.value).addminutes(-mark.limitmm.value).addseconds(-mark.limitss.value);
                    //修改倒计时任务;
                    updateqz(mark.auctionid, mark.id, endtime, limittime);


                    //追加 剩余时间 和 当前结束时间;
                    mark.surplustime = "";
                    mark.endtime = endtime;
                    var c1 = endtime.subtract(datetime.now);
                    var c2 = endtime.subtract(limittime);
                    if (c1 > c2)
                        mark.auctimestatus = 0;
                    else
                        mark.auctimestatus = 1;
                    service.updateany<markgoods>(mark, new list<string> { "surplustime", "endtime", "auctimestatus" });

                    return success();


                }








                //方法2
                //var mark = service.getiqueryable<markgoods>().firstordefault(x => x.id == mid);
                //if (mark == null)
                //    return;


                ////获取实际结束时间。
                //if (mark.surplustime.isnullorempty())
                //{
                //    return;
                //}
                //timespan.tryparse(mark.surplustime, out timespan surplustime);
                //timespan a = new timespan(1, 1, 1);
                ////结束时间  = 当前时间 + 剩余时间
                //var endtime = datetime.now.add(surplustime);
                ////获取限时竞价时间
                //var limittime = endtime.addhours(-mark.limithh.value).addminutes(-mark.limitmm.value).addseconds(-mark.limitss.value);
                ////新增倒计时任务;
                //addqz(mark.auctionid, mark.id, datetime.now, endtime, limittime);


                ////追加 剩余时间 和 当前结束时间;
                //mark.surplustime = "";
                //mark.endtime = endtime;
                //service.updateany<markgoods>(mark, new list<string> { "surplustime", "endtime" });


            }
            catch (exception ex)
            {

                throw;
            }

        }

以上代码均是提供思路,使用时需要进行代码简单改动。 

以上就是c# quartzs定时器的使用教程的详细内容,更多关于c# quartzs定时器的资料请关注其它相关文章!