Use Quartz. NET in ASP. NET MVC4 to execute a scheduled task, mvc4quartz.net
This article uses Quartz. NET to execute scheduled tasks in ASP. net mvc.
First install Quartz. NET through NuGet.
The general idea of using Quartz. NET is:
1. Implement the IJob interface to define specific tasks
2. Use the Quartz. net api to define scheduled task rules
3. Register a scheduled task in Application_Start
Implements the IJob interface.
public class MyJob : IJob
{
public void Execute(IJobExecutionContext context)
{
Debug.WriteLine("Hello at " + DateTime.Now.ToString());
}
}
Define rules in Global. asax and register them in Application_Start.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
MyJobs();
}
private static void MyJobs()
{
// Factory
ISchedulerFactory factory = new StdSchedulerFactory();
// Start
IScheduler scheduler = factory.GetScheduler();
scheduler.Start();
// Describe the work
IJobDetail jobDetail = new JobDetailImpl("mylittlejob",null, typeof(MyJob));
// Trigger
ISimpleTrigger trigger = new SimpleTriggerImpl("mytrigger",
null,
DateTime.Now,
null,
SimpleTriggerImpl.RepeatIndefinitely,
TimeSpan.FromSeconds(10));
// Execute
scheduler.ScheduleJob(jobDetail, trigger);
}