how to schedule a task in MVC4 C#?

二次信任 提交于 2019-11-28 08:13:26

Found this to be an awesome scheduler, FluentScheduler

Usage:

// Schedule an ITask to run at an interval
    Schedule<MyTask>().ToRunNow().AndEvery(2).Seconds();

You need a .Net Job Scheduler. Here is a good one: http://quartznet.sourceforge.net/

You can use ATrigger scheduling service. A .Net library is also available to create scheduled tasks without overhead. Errors log, Analytics, Tasks Listings and more benefits.

Disclaimer: I was among the ATrigger team. It's a freeware and I have not any commercial purpose.

maybe you wanna use a scheduled task. Doing this in a MVC is a bad idea (mixing responsabilities) and building a windows service looks like an overkill to me (because is something doesn't need to run all the time).

I use scheduled task of windows.

I have build a little app than enter a record in the bd, then access the website with this recordId(Guid) as a parameter.

In mvc i check if the id exist, if it exist i run tasks then delete the record in the db, if not i ignore it.

this way im able to add schedule with a param. without updating the app each time i need a new scheduled task. i just add a new task like "myapp.exe /MyNewTaskName"

hope this help someone ;-)

Baqer Naqvi

First of all;

  1. Add Nuget package Install-Package FluentScheduler
  2. Add your registry class that inherit Registry and some code
// Schedule a simple task to run at a specific time
Schedule(() => System.Diagnostics.Debug.Write("This is from service " + DateTime.Now.Second+"\n"))
               .ToRunNow().AndEvery(2).Seconds();
  1. Register that registry class in Application_Start of Global.asax.cs with TaskManager
TaskManager.Initialize(new Test());

GitHub

There is also a built-in option, QueueBackgroundWorkItem. It was added in .Net 4.5.2 and here is a guide on how to use it in MVC.

In addition to previously mentioned FluentScheduler you also have HangFire. And if you plan on deploying to Azure there's a handful of different services for this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!