Quantcast
Channel: ASP.NET 4.5 Hosting News (SuperBlogAds Network) » cheap asp.net 4.5 hosting
Viewing all articles
Browse latest Browse all 29

ASP.NET 4.5.2 Hosting – ASPHostPortal.com :: How You Can Run Background Tasks in ASP.NET

$
0
0

In it we details out a few gotchas which can be SO common when folks try to do function in the background. Go through it, but here is a summary from his post.

  • An unhandled exception in a thread not related using a ask for will consider down the method.
  • In the event you operate your site in a Web Farm, you could end up getting several circumstances of the app that all try to run the same task concurrently.
  • The AppDomain your site runs in can go down for a quantity of reasons and consider down your background task with it.

In the event you think you are able to just write a qualifications job oneself, it’s probably you will get it improper. I am not impugning your expertise, I’m just stating it’s subtle. Furthermore, why ought to you must?

ahp_freehostNET
There is certainly Lot of great techniques for you to do issues within the qualifications and a good deal of libraries and options accessible.

Some ASP.NET applications will probably be hosted in IIS in your data middle and others will probably be hosted in the Azure cloud. The spectrum of usage is around this, for my part:

  • Common: Hangfire (or comparable similar open supply libraries)
    employed for creating qualifications jobs inside your ASP.Net web site
  • Cloud: Azure WebJobs
    A formal Azure function used for offloading running of qualifications tasks beyond your web site and scale the workload
  • Advanced: Azure Worker Part within a Cloud Services
    scale the track record processing workload independently of your Web site and you need manage above the device

There is plenty of fantastic posts and videos on how to use Azure WebJobs, and plenty of documentation on how Employee Roles in scalable Azure Cloud Providers function, although not a whole lot about how your hosted ASP.Net software and easily have a very track record support. Here’s several.

WebBackgrounder

Because it says “WebBackgrounder is really a proof-of-concept of a web-farm helpful background job supervisor meant to simply perform with a vanilla ASP.Net net software.” Its code has not been touched in many years, Nevertheless the WebBackgrounder NuGet package has been downloaded almost a half-million occasions.

In case your ASP.NET software just needs a single background job to runs an a fundamental scheduled interval, than maybe you only want the basics of WebBackgrounder.

using System;
using System.Threading;
using System.Threading.Tasks;
 
namespace WebBackgrounder.DemoWeb
{
    public class SampleJob : Job
    {
        public SampleJob(TimeSpan interval, TimeSpan timeout)
            : base("Sample Job", interval, timeout)
        {
        }
 
        public override Task Execute()
        {
            return new Task(() => Thread.Sleep(3000));
        }
    }
}

Inbuilt: QueueBackgroundWorkItem – Additional in .NET 4.5.2

Relatively in reaction for the want for WebBackgrounder, .NET 4.5.2 added QueueBackgroundWorkItem as a new API. It’s not only a “Task.Run,” it tries to be a lot more :

QBWI schedules a task which may operate within the background, independent of any request. This differs from a normal ThreadPool work item in that ASP.NET instantly retains track of the amount of work items registered via this API are currently operating, and the ASP.Internet runtime will attempt to delay AppDomain shutdown until these perform things have concluded executing.

It could attempt to delay an AppDomain for so long as 90 seconds in order to allow your job to accomplish. If you cannot end in 90 seconds, then you’ll need a special (and even more strong, that means, from process) approach.

The API is pretty easy, getting Func<CancellationToken, Task>. Here’s an example that kicks of the track record perform item from an MVC action:

public ActionResult SendEmail([Bind(Include = "Name,Email")] User user)
{
    if (ModelState.IsValid)
    {
       HostingEnvironment.QueueBackgroundWorkItem(ct => SendMailAsync(user.Email));
       return RedirectToAction("Index", "Home");
    }
 
    return View(user);
}

FluentScheduler

FluentScheduler is actually a a lot more refined and sophisticated scheduler that includes a (you guessed it) fluent interface. You have truly specific manage over whenever your duties operate.

using FluentScheduler;
 
public class MyRegistry : Registry
{
    public MyRegistry()
    {
        // Schedule an ITask to run at an interval
        Schedule<MyTask>().ToRunNow().AndEvery(2).Seconds();
 
        // Schedule a simple task to run at a specific time
        Schedule(() => Console.WriteLine("Timed Task - Will run every day at 9:15pm: " + DateTime.Now)).ToRunEvery(1).Days().At(21, 15);
 
        // Schedule a more complex action to run immediately and on an monthly interval
        Schedule(() =>
        {
            Console.WriteLine("Complex Action Task Starts: " + DateTime.Now);
            Thread.Sleep(1000);
            Console.WriteLine("Complex Action Task Ends: " + DateTime.Now);
        }).ToRunNow().AndEvery(1).Months().OnTheFirst(DayOfWeek.Monday).At(3, 0);
    }
}

FluentScheduler also embraces IoC and might easily plug into your favorite Dependency Injection instrument of option by just implementing their ITaskFactory interface.

Quartz.Net

Quartz.Net is actually a .Net port in the well-liked Java work scheduling framework from the (virtually) identical identify. It really is very actively developed. Quartz has an IJob interface with only one approach, Execute, to implement.

using Quartz;
using Quartz.Impl;
using System;
 
namespace ScheduledTaskExample.ScheduledTasks
{
    public class JobScheduler
    {
        public static void Start()
        {
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
            scheduler.Start();
 
            IJobDetail job = JobBuilder.Create<MyJob>().Build();
 
            ITrigger trigger = TriggerBuilder.Create()
                .WithDailyTimeIntervalSchedule
                  (s =>
                     s.WithIntervalInHours(24)
                    .OnEveryDay()
                    .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0))
                  )
                .Build();
 
            scheduler.ScheduleJob(job, trigger);
        }
    }
}

Then, within your Application_Start, you call JobScheduler.Start(). There is a excellent starting out post on Quartz at Mikesdotnetting you need to take a look at.

Hangfire

And final but undoubtedly not minimum, essentially the most polished (IMHO) from the group, Hangfire by @odinserj. It is a wonderful framework for background employment in ASP.Internet. It really is even optionally backed by Redis, SQL Server, SQL Azure, MSMQ, or RabbitMQ for trustworthiness.

The Hangfire documentation is remarkable, really. Each and every open source project’s doc should be this polished. Heck, ASP.NET’s documentation needs to be this good.

The most effective feature from Hangfire is its constructed in /hangfire dashboard that displays you your scheduled, processing, succeeded and unsuccessful jobs. It’s truly a pleasant polished addition.

1

You’ll be able to enqueue “fire and forget” employment easily and so they are backed by persistent queues:

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

 You can delay them…

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

Or great extremely refined CRON fashion recurrent duties:

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

Hangfire is simply a joy.


Viewing all articles
Browse latest Browse all 29

Trending Articles