Parse the open-source. NET timing Task component Hangfire,. nethangfire

Source: Internet
Author: User

Parse the open-source. NET timing Task component Hangfire,. nethangfire

The project is about to start soon. Many garden friends are asking this question. It seems that everyone is very concerned about this matter. We need to write a project that we are satisfied with step by step. In the past, many people complained that this was not good. In addition, this person cannot stop talking about it, and sometimes he may say something very emotional, therefore, write as few blog posts as possible. (If there are deficiencies in the blog post, I still hope to correct them more, and I will modify them in time. If I just click here and say something radical, then I am not very happy)

A scheduled task is often used in projects. NET does not have much technology to complete scheduled tasks ,. NET Framework has a "built-in" timer function, through the System. timers. timer class. Problems to be faced when using the Timer class: There is no persistence Mechanism for the Timer; there is an inflexible plan for the Timer (only the start time and repetition interval can be set, not based on the date, time, etc ); the timer does not use a thread pool (each timer has one thread); there is no real management solution for the timer-you must write your own mechanism to be able to remember, organize and retrieve the task name and so on. If you need to implement the timer function in. NET, you can try to use the following open-source free Quartz. Net component.

The above two methods are introduced. Here we will introduce another component, namely the Hangfire component.

1. Hangfire component Overview

A Simple Method for Performing background processing in. NET and. NET Core applications. No need for Windows Services or separate processes. Supported by persistent storage, such as sqlserver, redis, and mongodb. Hangfire supports all types of background tasks-short run and long run, CPU-intensive and I/O-intensive, one-time and periodic.

1. component features:

2. component functions:

Public void Configuration (IAppBuilder app) {GlobalConfiguration. Configuration. UseSqlServerStorage ("<connection string or its name>"); app. UseHangfireDashboard (); app. UseHangfireServer ();}

GlobalConfigurationClass is the preferred way to configure Hangfire. This is the entry point for some methods, including methods from third-party storage implementations or other extensions. Easy to use, justHangfireInclude the namespace in the application initialization class and findGlobalConfiguration.ConfigurationAttribute Extension Method

2. console settings:

 GlobalConfiguration.Configuration                .UseColouredConsoleLogProvider()               
          .UseSqlServerStorage(@"Server=.\sqlexpress;Database=Hangfire.Sample;Trusted_Connection=True;") .UseMsmqQueues(@".\Private$\hangfire{0}", "default", "critical");

3. queue-based task processing:

var jobId = BackgroundJob.Enqueue(    () => Console.WriteLine("Fire-and-forget!"));

4. Delayed task execution:

var jobId = BackgroundJob.Schedule(    () => Console.WriteLine("Delayed!"),    TimeSpan.FromDays(7));

5. Cyclic task execution:

RecurringJob.AddOrUpdate(    () => Console.WriteLine("Recurring!"),    Cron.Daily);

6. Continue execution when the parent job is completed:

BackgroundJob.ContinueWith(    jobId,    () => Console.WriteLine("Continuation!"));

7. batch processing method:

var batchId = BatchJob.StartNew(x =>{    x.Enqueue(() => Console.WriteLine("Job 1"));    x.Enqueue(() => Console.WriteLine("Job 2"));});

8. When all background jobs in the parent batch are completed, the batch processing continues:

BatchJob.ContinueWith(batchId, x =>{    x.Enqueue(() => Console.WriteLine("Last Job"));});

 9.Use IoC container:

public  class  ContainerJobActivator  : JobActivator {     private  IContainer  _container ;    public  ContainerJobActivator (IContainer  container )    {         _container  =  container ;     }}    public  override  object  ActivateJob (Type  type )    {         return  _container 。Resolve (type );     } }

Register the Hangfire server as the current job initiator before starting the Hangfire server.

var container = new Container();GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(container));...app.UseHangfireServer();

 

Hangfire saves jobs to persistent storage and processes them reliably. This means that you can stop the Hangfire working thread, uninstall the application domain, or even terminate the process, and the work will be processed. Hangfire marks the job as completed. Only when the last line of code is executed and the job may fail and the last line is known. It includes different automatic retry functions to handle stored errors or errors in the code.

Iii. Analysis of core objects of the Hangfire component

The common methods of the Hangfire component are introduced above. There are many functions of the Hangfire component. Here we will introduce it. If you are interested, go to the official website to view the api. The following describes some core objects of the Hangfire component and explores the deep-seated problems of the Hangfire component.

 1. RecurringJob. AddOrUpdate ():

 public static void AddOrUpdate(            Expression<Action> methodCall,            string cronExpression,            TimeZoneInfo timeZone = null,            string queue = EnqueuedState.DefaultQueue)        {            var job = Job.FromExpression(methodCall);            var id = GetRecurringJobId(job);            Instance.Value.AddOrUpdate(id, job, cronExpression, timeZone ?? TimeZoneInfo.Utc, queue);        }

This method is used to trigger a scheduled job multiple times on a specified CRON plan. This method has 16 reloads, Job. FromExpression (methodCall); used to obtain the Expression Tree for calling a method given by a new instance based on the Job class. The GetRecurringJobId (job) method obtains the corresponding JobID Based on the Job object.

2. BackgroundJob. Enqueue ():

public static string Enqueue([NotNull, InstantHandle] Expression<Action> methodCall)        {            var client = ClientFactory();            return client.Enqueue(methodCall);        }

This method creates a new fire-and-forget job based on the given method call expression. This method accepts a parameter, indicating the method call expression that will be grouped to the server. Next, let's take a look at the specific implementation of var client = ClientFactory ();

internal static Func<IBackgroundJobClient> ClientFactory        {            get            {                lock (ClientFactoryLock)                {                    return _clientFactory ?? DefaultFactory;                }            }            set            {                lock (ClientFactoryLock)                {                    _clientFactory = value;                }            }        }

This attribute defines a generic delegate for Func <IBackgroundJobClient>. This attribute is a readable and writable operation that locks ClientFactoryLock to prevent deadlocks.

Iv. Summary

The above briefly introduces the background and some simple applications of the Hangfire component, and also focuses on some objects. This component has powerful functions and needs to be understood in many places. This article cannot be fully described and can be used as a reference. Here, I want to comment out that Microsoft's technology has developed too fast recently and many technologies have not yet been developed. New technologies are coming out, which makes us at the bottom of the layer really uncomfortable, things have a regular development. It is not something that was lacking in the past that can be supplemented in a short time, but it still needs to leave enough space.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.