简体   繁体   中英

Run a task schedule within asp.net application?

I have an asp.net application which needs to call an API very 5 minutes to get the latest data from a server. Currently, we plan to 1) build a console application and then use windows server task scheduler to schedule it; or, 2) build a windows service for this.

Is it possible to do this within asp.net application? If yes, how?

We just want to see whether there are better solution out there.

thanks

As of .NET 4.5.2 there is a QueueBackgroundWorkItem API that allows you to create your own reoccuring task implementation ( see here for details and examples ) however I would recommend taking a look at some popular and more established open source libraries available. The most popular being hangfire.io

After installing it via Nuget ( PM> Install-Package Hangfire ) and configuring it with your ASP.NET MVC application like so:

public void Configuration(IAppBuilder app)
{
    GlobalConfiguration.Configuration.UseSqlServerStorage("<connection string or its name>");

    app.UseHangfireDashboard(); //optional
    app.UseHangfireServer(); 
}

You can start to create fire and forget schedules, delayed or reoccurring schedules like so:

BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget"));
BackgroundJob.Schedule(() => Console.WriteLine("Delayed"), TimeSpan.FromDays(1));
RecurringJob.AddOrUpdate(() => Console.WriteLine("Daily Job"), Cron.Daily);

What's also really nice about Hangfire is that it's got a really polished reporting feature that allows you to monitor your sheduled tasks:

在此处输入图片说明

You can see more screenshots of the reporting dashboard here .

ASP.Net is really for providing an HTML user interface to users. As the solution you are wanting does not need a user interface, creating it as an ASP.Net application makes the job of installing and maintaining the application that much harder.

Here is a post talking about the dangers of recurring background tasks in ASP.NET, it includes examples of how to do it. Probably best to use a library such as Hangfire to avoid doing it yourself.

As another option, you can even create a powershell script that is kicked off by the task scheduler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM