In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the use of C # Quartzs timer". In daily operation, I believe many people have doubts about the use of C # Quartzs timer. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what is the use of C # Quartzs timer?" Next, please follow the editor to study!
Preface
First of all, I think of the countdown and scheduled tasks. All you can think of is a timer. Then timers play an important role in web and winfrom programs. Does it exist like a timer on the server side?
With these requirements, I found a third-party component Quartz.Net to implement (source location)
Implementation steps
(1) the first step is to download the Quartz.Net component through NuGet and reference it to the current project
(2) create two classes, one is the operation class, the other inherits IJob and needs to implement the method of IJob.
/ public class Operation: BaseBusiness {# region instantiates public Operation () {_ options = new Options ();} internal IOptions _ options {get;} # endregion public static IScheduler scheduler; public static ISchedulerFactory factory / get the cron expression / time / 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;} / Delete the group name public void RemoveJob (string Id, string MarkGoodsId, string GroupName) {/ / var jobKey = new JobKey (GroupName + Id + MId + "j", GroupName) of the primary key / job of the auction data object. Var job = new JobKey (GroupName + Id + MarkGoodsId + "j", GroupName); scheduler.DeleteJob (job);} / / clear all scheduled tasks 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 / / record the difference between two times 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 + "days" + hours + "hours" + minutes + "minutes" + seconds + "seconds"; / / push countdown PushHelper.AuctionCountDown (markId, days, hours, minutes, seconds); / / getTriggerState}) } / set ID public void AddQz (DateTime BeginTime, DateTime FreeTime) {var GroupName = _ options.GetPKById ("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) {/ / delete task scheduler.DeleteJob (jobKey) } / / set Job StatefulJob var job = JobBuilder.Create () .WithIdentity (GroupName + Id + MId + "j", GroupName) .build (); job.JobDataMap.Put ("FreeTime", FreeTime) / / [method 1] set 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 () / / [method 2] / / var ExecSs = "0ram 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);}}
The above is a simple package that can be pushed according to this countdown. Add some encapsulation such as pause, resume, end, update, etc.
The call only needs to be simply instantiated to make the call.
And then I'm going to talk about other encapsulation ideas and code snippets.
Delay countdown:
Make a modification according to the passed parameter time, delete the previous task and restart a task.
/ [auction delay] modify the countdown task / public void UpdateQz (String Id, string Mid, DateTime FreeTime, DateTime LimitTime) {/ / scheduler = factory.GetScheduler () .Result; / / if (scheduler = = null) / / return / / var GroupName = _ options.GetPKById ("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 (); / / end time of modification 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) / / Delete the task scheduler.DeleteJob (jobKey); scheduler.ScheduleJob (job, newTrigger); / / modify the scheduled task that ends. SetAuctioneds setAuctioneds = new SetAuctioneds (); setAuctioneds.SetEndQz (Id, FreeTime, Mid);}
The countdown pauses:
Call the PauseTrigger method of the component to pause / public AjaxResult StopQz (string Id, string MId) {try {/ / method 1 / / auction in progress var GroupName = _ options.GetPKById ("1316283839361847296"). ToString (); var mark = Service.GetIQueryable (). FirstOrDefault (x = > x.Id = = MId); if (mark = = null) return Error ("cannot find the target!") / / get the actual end time. Var subEndTime = mark.EndTime.Value; / / time remaining after the calculation is paused = audEndTime (end time)-current time var nowEndTime = DateTime.Now; var DifferTime = subEndTime.Subtract (nowEndTime); / / append remaining time and current end time 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 ("failure: this task does not exist!") ;} if (Result = = TriggerState.Paused) / / pause {return Success ("failed: the task has been paused!") ;} else {scheduler.PauseTrigger (TriKey); mark.AucTimeStatus = 2; Service.UpdateAny (mark, new List {"SurplusTime", "AucTimeStatus"}); return Success ("success: task paused") } / / method 2 / / var mark = Service.GetIQueryable () .FirstOrDefault (x = > x.Id = = MId); / / if (mark = = null) / / return; / get the actual end time. / / var subEndTime = mark.EndTime.Value; / time remaining after the calculation is paused = audEndTime (end time)-current time / / var nowEndTime = DateTime.Now; / / var DifferTime = subEndTime.Subtract (nowEndTime); / append remaining time and current end time / / mark.SurplusTime = DifferTime.ToString (); / mark.EndTime = nowEndTime; / / Service.UpdateAny (mark, new List {"SurplusTime"}); / auction in progress / / var GroupName = _ options.GetPKById ("1316283839361847296"). ToString (); / / close the timer / / RemoveJob (mark.AuctionId, mark.Id, GroupName) } catch (Exception) {throw;}}
Countdown to resume:
As the saying goes, a broken mirror is hard to round, and it is difficult to get back the water that has been spilled. The same is true for recovery, for example: the countdown to 7 pauses, so how to resume from 7? This involves the involvement of timestamps and storage in the database.
/ resume countdown / public AjaxResult ReturnQz (string Id, string MId) {try {var mark = Service.GetIQueryable () .FirstOrDefault (x = > x.Id = = MId); if (mark = = null) return Error () / / get the actual end time. If (mark.SurplusTime.IsNullOrEmpty ()) {return Error ();} TimeSpan.TryParse (mark.SurplusTime, out TimeSpan surplusTime); / / method 1 / / auction in progress / / auction in progress var GroupName = _ options.GetPKById ("1316283839361847296"). ToString () Var TriKey = new TriggerKey (GroupName + Id + MId + "t", GroupName); var Result = scheduler.GetTriggerState (TriKey) .result; if (Result = = TriggerState.None) {return Error ("failure: this task does not exist!") ;} if (Result = = TriggerState.Normal) / / pause {return Error ("failure: the task is in progress and no recovery is needed!") ;} else {/ / end time = current time + remaining time var endTime = DateTime.Now.Add (surplusTime) / / get the limited bidding time var LimitTime = endTime.AddHours (- mark.LimitHH.Value). AddMinutes (- mark.LimitMM.Value). AddSeconds (- mark.LimitSS.Value); / / modify the countdown task UpdateQz (mark.AuctionId, mark.Id, endTime, LimitTime); / / append remaining time and current end time 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 (mark, new List {"SurplusTime", "EndTime", "AucTimeStatus"}); return Success ();} / / method 2 / / var mark = Service.GetIQueryable () .FirstOrDefault (x = > x.Id = = MId) / / if (mark = = null) / / return; / get the actual end time. / / if (mark.SurplusTime.IsNullOrEmpty ()) / / {/ / return; / /} / / TimeSpan.TryParse (mark.SurplusTime, out TimeSpan surplusTime); / / TimeSpan a = new TimeSpan (1,1,1) / end time = current time + remaining time / / var endTime = DateTime.Now.Add (surplusTime); / get time-limited bidding time / / var LimitTime = endTime.AddHours (- mark.LimitHH.Value). AddMinutes (- mark.LimitMM.Value). AddSeconds (- mark.LimitSS.Value) / added countdown task / / AddQz (mark.AuctionId, mark.Id, DateTime.Now, endTime, LimitTime); / append remaining time and current end time / / mark.SurplusTime = ""; / / mark.EndTime = endTime; / / Service.UpdateAny (mark, new List {"SurplusTime", "EndTime"});} catch (Exception ex) {throw }} at this point, the study on "what is the use of C # Quartzs timer" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.