2012-09-06 5 views
1

ASP.NET MVC에 새로운 기능이 있습니다. 저는 Rails와 PHP MVC FM과 같은 다른 MVC 프레임 워크에 익숙합니다.asp.net mvc를 사용하여 하루에 한 번 함수를 실행하는 방법은 무엇입니까?

ASP.NET MVC 내부에서 동시에 한 번씩 일부 기능을 실행해야합니다. 어떻게해야합니까? 이 함수가 데이터베이스를 업데이트하고 싶습니다.

리눅스에서는 Cron이 하루에 한 번 액세스하는 서버에 URL을 넣을 수 있지만 Windows에서 가장 좋은 방법은 모르겠다.

+3

를 사용하여 바로 작업에 적합한 도구입니다. 서버에서 예약 된 작업을 만들어 관리하십시오. – asawyer

+0

서비스를 원하고있는 것처럼 들리거나 그런 효과가있는 것으로 들립니다. Windows 작업 스케줄러 또는 Windows 서비스를 살펴보십시오. –

+0

요청한 시간에 작업을 시작하는 작업자 프로세스가 계속 보장 될 수는 없습니다. 어쩌면 그냥 재활용해야할까요? 그래서 나는 asawyer에 동의합니다 ... –

답변

0

은 기본적으로 당신은 web.config 파일에 두 appSettings는 추가해야합니다 :

<appSettings> 
    . 
    <add key="TimerStartTime" value="09:00:00 PM"/> 
    <add key="TimerIntervalInMilliseconds" value="3000000"/> 
</appSettings> 

그런 다음 Global.asax.cs 파일에 수정 및 추가 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Http; 
using System.Web.Mvc; 
using System.Web.Optimization; 
using System.Web.Routing; 
// Added the following for the timer related code 
using System.Diagnostics; 
using System.Timers; 
using System.Web.Configuration; 

namespace TestVSOnline01 
{ 
    public class MvcApplication : System.Web.HttpApplication 
    { 
     // Added this class visible variable to hold the timer interval so it's not gotten from the 
     // web.config file on each Elapsed event of the timer 
     private static double TimerIntervalInMilliseconds = 
      Convert.ToDouble(WebConfigurationManager.AppSettings["TimerIntervalInMilliseconds"]); 

     protected void Application_Start() 
     { 
      AreaRegistration.RegisterAllAreas(); 
      GlobalConfiguration.Configure(WebApiConfig.Register); 
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 
      BundleConfig.RegisterBundles(BundleTable.Bundles); 

      // Added the following within the Application_Start() procedure: 
      // ******************************************************************************************* 
      // The values used in this example will cause your processes to run sometime 
      // between 09:00:00 PM and 09:05:00 PM, with the timer Elapsed event being raised 
      // every 300000ms (5 minutes) 
      // 
      // The following AppSettings were added to Web.config: 
      // TimerStartTime 
      // TimerIntervalInMilliseconds 
      // You can use a simple text editor to change your start time and/or timer interval without 
      // having to modify your code, recompile, and republish it. 
      // 
      // The shorter the interval, then smaller the time window in which the processes will run, but 
      // the more frequently all of this code and event firing is happening. But you could set the 
      // interval to 1000ms and have you events run right at the time specified. 
      // 
      // !!! NOTE: The web.config file is not designed for constant updates. When an ASP.NET 
      // !!! application launches a watch is put on the web.config file. ASP.NET will detect if the 
      // !!! web.config changes while the application is running. When ASP.NET detects a change it 
      // !!! will spin up a new version of the application with the new settings in effect. Any in 
      // !!! process information, such as data kept in Session, Application, and Cache will be lost 
      // !!! (assuming session state is InProc and not using a state server or database). 
      // !!! (Source: http://odetocode.com/Articles/345.aspx) 
      // 
      // ******************************************************************************************* 

      // The Debug.WriteLine calls are for watching the progress in the Output Window 
      // in Visual Studio - Remove or comment out if you like 

      Debug.WriteLine(string.Concat("Application_Start Called: ", DateTime.Now.ToString())); 

      // This will raise the Elapsed event every 'x' millisceonds (whatever you set in the 
      // Web.Config file for the added TimerIntervalInMilliseconds AppSetting 
      Timer timer = new Timer(TimerIntervalInMilliseconds); 

      timer.Enabled = true; 

      // Setup Event Handler for Timer Elapsed Event 
      timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); 

      timer.Start(); 
     } 

     // Added the following procedure: 
     static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
     { 
      // Get the TimerStartTime web.config value 
      DateTime MyScheduledRunTime = DateTime.Parse(WebConfigurationManager.AppSettings["TimerStartTime"]); 

      // Get the current system time 
      DateTime CurrentSystemTime = DateTime.Now; 

      Debug.WriteLine(string.Concat("Timer Event Handler Called: ", CurrentSystemTime.ToString())); 

      // This makes sure your code will only run once within the time frame of (Start Time) to 
      // (Start Time+Interval). The timer's interval and this (Start Time+Interval) must stay in sync 
      // or your code may not run, could run once, or may run multiple times per day. 
      DateTime LatestRunTime = MyScheduledRunTime.AddMilliseconds(TimerIntervalInMilliseconds); 

      // If within the (Start Time) to (Start Time+Interval) time frame - run the processes 
      if ((CurrentSystemTime.CompareTo(MyScheduledRunTime) >= 0) && (CurrentSystemTime.CompareTo(LatestRunTime) <= 0)) 
      {     
       Debug.WriteLine(String.Concat("Timer Event Handling MyScheduledRunTime Actions: ", DateTime.Now.ToString())); 
       // RUN YOUR PROCESSES HERE 
      } 
     } 
    } 
} 

가 청소, 그것의 아주 간단합니다. 아래의 코드는 당신이 Global.asax.cs 파일에 추가 할 필요 단지 단순화 된 버전입니다합니다 (여전히 web.config appSettings는 추가 잊지 마세요) :

// Added the following for the timer related code 
using System.Diagnostics; // Can remove this reference if you remove all the Debug.Writeline entries 
using System.Timers; 
using System.Web.Configuration; 

// Add the following to the top of the main class, outside of any subroutines: 
private static double TimerIntervalInMilliseconds = Convert.ToDouble(WebConfigurationManager.AppSettings["TimerIntervalInMilliseconds"]); 

// Add the following to the end of the Application_Start() subroutine: 
Timer timer = new Timer(TimerIntervalInMilliseconds); 
timer.Enabled = true; 
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); 
timer.Start(); 

// Added the following procedure: 
static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    {  
     DateTime MyScheduledRunTime = DateTime.Parse(WebConfigurationManager.AppSettings["TimerStartTime"]); 
     DateTime CurrentSystemTime = DateTime.Now; 
     DateTime LatestRunTime = MyScheduledRunTime.AddMilliseconds(TimerIntervalInMilliseconds); 
     if ((CurrentSystemTime.CompareTo(MyScheduledRunTime) >= 0) && (CurrentSystemTime.CompareTo(LatestRunTime) <= 0)) 
     {     
      // RUN YOUR PROCESSES HERE 
     } 
    } 
관련 문제