Timing Task Scheduling Based on Quartz.Net Component in Window s Service

Preface:

In The previous chapter In this paper, we use console to achieve scheduling of timed tasks, and have a general understanding of how to implement tasks based on Quartz.Net components, including at least three parts: job (job), trigger (trigger), scheduler (scheduler). Job is the business logic that needs to be executed in a timed task. trigger specifies when and according to what rules it will execute. Finally, job and trigger will be registered in scheduler. Scheduler is used to coordinate the collocation of job and trigger.

Do you encounter the need for software to perform tasks automatically in your work, but you don't want to start the software directly to perform tasks manually?  

                         

At this time, we can consider using window s services, polling database synchronization based on Quartz.Net components, regular email notification, regular data processing and other functions.

Start:

First create a windows service project

In the created project, click "Click Here to Switch to Code View" in the Service1.cs file to switch to code

At this point we can notice two ways: OnStart (service start) and OnStop (service stop)

        /// <summary>
        /// Service startup
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
        }
        /// <summary>
        /// Service discontinuation
        /// </summary>
        protected override void OnStop()
        {
        }

First, create a scheduler reference:

            ISchedulerFactory schedFact = new StdSchedulerFactory();
            IScheduler sched = await schedFact.GetScheduler();

2. Start scheduler:

            await sched.Start();

Implementing IJob:

SyncJob.cs implements IJob and writes the business logic to be processed in Execute method. The system will process it regularly according to the configuration of Quartz.

    [Invoke(Name = "SyncJob", Remark = "Quartz service", Group = "Quartz Service management", Begin = "2018-05-01 12:00:00", Interval = 5)]
    public class SyncJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                //Get the current time for each execution and output the current time
                //Here you can write the methods you need for each timing execution
                LogHelper.SaveLog("Output log", "At the present time:" + DateTime.Now + "--Last execution time:" + DateTime.Now.AddSeconds(-5));
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
            }

            return null;
        }
    }

4. Create trigger: (Establish a trigger at a certain time point and execute it every 5 seconds)

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")  //Flip-flop group
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever())
                .Build();

5. Triggers perform tasks:

            await sched.ScheduleJob(job, trigger);

Integrate several steps into the following code:

        /// <summary>
        /// Service startup
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            Run().GetAwaiter().GetResult();
            LogHelper.SaveLog("service", "start");
        }
        /// <summary>
        /// Service discontinuation
        /// </summary>
        protected override void OnStop()
        {
            try
            {
                if (scheduler != null)
                {
                    scheduler.Shutdown();
                }
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
            }
            LogHelper.SaveLog("service", "End");
        }

        IScheduler scheduler;
        private async Task Run()
        {
            try
            {
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                scheduler = await factory.GetScheduler();

                await scheduler.Start();
                Jobs.Jobs.Config(scheduler);
            }
            catch (SchedulerException ex)
            {
                LogHelper.SaveLog(ex);
            }

        }

install

Open cmd as Administrator

 

Function:

The effect of executing once every 5 seconds:

Output data through log to see the effect

Additional:

Delete services

Open cmd as Administrator

 

2. Debugging Windows Services

1) Install and run services

 

2) Additional processes

3) Add breakpoints to the code for debugging

Summary:

1. When we need to perform tasks on time, we can consider using the combination of window s services and quartz components to achieve the task on time. This is also a method that can be implemented in many scenarios, such as: timing polling database synchronization, timing mail notification, timing data processing, etc.

2. Display the current tasks and execution through management tools, and debug the problems encountered in Window s services by debugging tools.

3. Quatz has many more uses, you can refer to: Quartz.Net Official Document And Quartz.Net Open Source Address

Keywords: C# Database Windows

Added by nishmgopla on Sun, 18 Aug 2019 14:44:59 +0300