Sunteți pe pagina 1din 12

Table of Contents

Hangfire...................................................................................................................... 1
Client...................................................................................................................... 2
Server....................................................................................................................... 3
Add a job............................................................................................................... 3
and relax.............................................................................................................. 4

Hangfire
Three main components:

Client,

Storage and

Server.

MILO DAVITKOVI 1
Client
Background jobs:

o Fire-and-forget (to offload the method invocation),


o Delayed (to perform the call after some time) and
o Recurring (to perform methods hourly, daily and so on).

Background jobs are based on regular static or instance methods invocation.

var client = new BackgroundJobClient();

client.Enqueue(() => Console.WriteLine("Easy!"));

client.Delay(() => Console.WriteLine("Reliable!"), TimeSpan.FromDays(1));

C# Class members static


It means no matter how many objects of the class are created, there is only
one copy of the static member.

A static member is shared by all objects of the class. All static data is
initialized to zero when the first object is created, if no other initialization is present

C# Function member as static


You make it independent of any particular object of the class. A static member
function can be called even if no objects of the class exist and the static functions
are accessed using only the class name and the scope resolution operator ::.

A static member function can only access static data member, other static
member functions and any other functions from outside the class.

Static member functions have a class scope and they do not have access to
the this pointer of the class. You could use a static member function to determine
whether some objects of the class have been created or not.

MILO DAVITKOVI 2
There is also more easy way to create background jobs the BackgroundJob
class that allows you to use static methods to perform the creation task.

BackgroundJob.Enqueue(() => Console.WriteLine("Hello!"));

Job Storage
Hangfire keeps background jobs and other information that relates to the
processing inside a persistent storage. Persistence helps background jobs to survive
on application restarts, server reboots, etc.

Server
Background jobs are processed by Hangfire Server. It is implemented as a set
of dedicated (not thread pools) background threads that fetch jobs from a storage
and process them. Server is also responsible to keep the storage clean and remove
old data automatically.

All you need is to create an instance of the BackgroundJobServer class and start the
processing:

using (new BackgroundJobServer())

Console.WriteLine("Hangfire Server started. Press ENTER to exit...");

Console.ReadLine();

OWIN Startup class


Every OWIN Application has a startup class where you specify components for
the application pipeline. There are different ways you can connect your startup class

MILO DAVITKOVI 3
with the runtime, depending on the hosting model you choose (OwinHost, IIS, and
IIS-Express).

Add a job
Hangfire handles different types of background jobs, and all of them are invoked on
a separate execution context.

Fire-and-forget

This is the main background job type, persistent message queues are used to
handle it. Once you create a fire-and-forget job, it is saved to its queue ("default" by
default, but multiple queues supported). The queue is listened by a couple of
dedicated workers that fetch a job and perform it.

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

These jobs are executed only once and almost immediately after they fired.

var jobId = BackgroundJob.Enqueue(


() => Console.WriteLine("Fire-and-forget!"));

Delayed

If you want to delay the method invocation for a certain type, call the following
method. After the given delay the job will be put to its queue and invoked as a
regular fire-and-forget job.

MILO DAVITKOVI 4
BackgroundJob.Schedule(() => Console.WriteLine("Delayed"),
TimeSpan.FromDays(1));

Delayed jobs are executed only once too, but not immediately only after the specified
time interval.

var jobId = BackgroundJob.Schedule(


() => Console.WriteLine("Delayed!"),
TimeSpan.FromDays(7));

Recurring

To call a method on a recurrent basis (hourly, daily, etc), use the RecurringJob class.
You are able to specify the schedule using CRON expressions to handle more
complex scenarios.

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

Recurring jobs fired many times on the specified CRON schedule.

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

Continuations

Continuations allow you to define complex workflows by chaining multiple


background jobs together.

MILO DAVITKOVI 5
var id = BackgroundJob.Enqueue(() => Console.WriteLine("Hello, "));

BackgroundJob.ContinueWith(id, () => Console.WriteLine("world!"));

Continuations are executed when parent job has been finished.

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

Continuations allow you to define complex workflows by chaining multiple


background jobs together.

var id = BackgroundJob.Enqueue(() => Console.WriteLine("Hello, "));


BackgroundJob.ContinueWith(id, () => Console.WriteLine("world!"));

Batches

Batch is a group of background jobs created atomically.

var batchId = Batch.StartNew(x =>


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

Batch Continuations

Batch continuation is fired when all background jobs in a parent batch finished.

Batch.ContinueWith(batchId, x =>
{

MILO DAVITKOVI 6
x.Enqueue(() => Console.WriteLine("Last Job"));
});

and relax
Hangfire saves your jobs into persistent storage and processes them in a
reliable way. It means that you can abort Hangfire worker threads, unload
application domain or even terminate the process, and your jobs will be processed
anyway. Hangfire flags your job as completed only when the last line of your code
was performed, and knows that the job can fail before this last line. It contains
different auto-retrying facilities, that can handle either storage errors or errors
inside your code.

This is very important for generic hosting environment, such as IIS Server.
They can contain different optimizations, timeouts and error-handling code (that
may cause process termination) to prevent bad things to happen. If you are not
using the reliable processing and auto-retrying, your job can be lost. And your end
user may wait for its email, report, notification, etc. indefinitely.

Clean Temp Directory Process

Background Process

Use them when you need to run background processes continuously throught
the lifetime of your application.

public class CleanTempDirectoryProcess : IBackgroundProcess


{
public void Execute(BackgroundProcessContext context)
{

MILO DAVITKOVI 7
Directory.CleanUp(Directory.GetTempDirectory());
context.Wait(TimeSpan.FromHours(1));
}
}

Configuring Authorization
Hangfire Dashboard exposes sensitive information about your background jobs,
including method names and serialized arguments as well as gives you an
opportunity to manage them by performing different actions retry, delete, trigger,
etc. So it is really important to restrict access to the Dashboard.

Change URL Mapping


By default, UseHangfireDashboard method maps the Dashboard to the /hangfire
path. If you want to change this for one reason or another, just pass your URL path.

Change Back to site Link


By default, Back to site link (top-right corner of Dashboard) leads you to the root
URL of your application. In order to change it, use the DashboardOptions class.

Multiple Dashboards
You can also map multiple dashboards that show information about different
storages.

Calling methods in background

Fire-and-forget method invocation has never been simpler. As you already know
from the Quick start guide, you only need to pass a lambda expression with the
corresponding method and its arguments:

MILO DAVITKOVI 8
BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));

The Enqueue method does not call the target method immediately, it runs the
following steps instead:

Serialize a method information and all its arguments.

Create a new background job based on the serialized information.

Save background job to a persistent storage.

Enqueue background job to its queue.

Calling methods with delay

Sometimes you may want to postpone a method invocation; for example, to


send an email to newly registered users a day after their registration. To do this, just
call the BackgroundJob.Schedule method and pass the needed time span:

BackgroundJob.Schedule(

() => Console.WriteLine("Hello, world"),

TimeSpan.FromDays(1));

Hangfire Server periodically check the schedule to enqueue scheduled jobs to


their queues, allowing workers to perform them. By default, check interval is equal
to 15 seconds, but you can change it, just pass the corresponding option to the
BackgroundJobServer ctor.

Disable Idle Timeout set its value to 0.

Use the application auto-start feature.

TimeSpan.FromDays(1) 1 day after

TimeSpan.FromMinutes(1) 1 minute after

MILO DAVITKOVI 9
TimeSpan.FromSeconds(1) 1 second after

Performing recurrent tasks

Recurring job registration is just as simple as background job registration


you only need to write a single line of code:

RecurringJob.AddOrUpdate(() => Console.Write("Easy!"), Cron.Daily);

This line creates a new entry in persistant storage. A special component in


Hangfire Server (see Processing background jobs) checks the recurring jobs on a
minute-based interval and then enqueues them as fire-and-forget jobs. This enables
you to track them as usual.

Manipulating recurring jobs


RemoveIfExists
You can remove an existing recurring job by calling the RemoveIfExists
method. It does not throw an exception when there is no such recurring job.

RecurringJob.RemoveIfExists("some-id");

Trigger
To run a recurring job now, call the Trigger method. The information about
triggered invocation will not be recorded in the recurring job itself, and its next
execution time will not be recalculated from this running. For example, if you have a
weekly job that runs on Wednesday, and you manually trigger it on Friday it will run
on the following Wednesday.

RecurringJob.Trigger("some-id");

1
MILO DAVITKOVI
0
Using cancellation tokens

Hangfire provides support for cancellation tokens for your jobs to let them
know when a shutdown request was initiated, or job performance was aborted. In
the former case the job will be automatically put back to the beginning of its queue,
allowing Hangfire to process it after restart.

Noticed problems:

o trouble getting the Hangfire (1.5.8) dashboard to work inside of an IIS


Virtual Directory. Everything works beautifully in my dev environment
o I've just started using HangFire. The jobs seem to work fine when I run it
locally from IIS Express, but when I run it on my dev server I get errors that
no parameterless constructor defined.
o Hangfire didn't support less than a minute for recurring jobs. Why?
Imagine if they allow less than a minute, let say 1 sec. How frequent should
HangFire check recurring jobs in db? Bottom line is, it my hurt your database.
o Performance problems with huge amount of recurring jobs (1.500.000 Jobs)

With Hangfire

1
MILO DAVITKOVI
1
You can:
o Run Fire and Forget background jobs
o Run Delayed jobs
o Run Recurring jobs
o Make Continues jobs
o Manipulating with recurring jobs

You cant:
o Set up recurring jobs less then a minute

1
MILO DAVITKOVI
2

S-ar putea să vă placă și