MVC 定時執行任務

原文: MVC 定時執行任務

 

環境:.net4.5html

需求:須要一個方法定時執行任務post

解決: System.Threading.Timer 提供以指定的時間間隔執行方法的機制。 此類不能被繼承,有10多種實例化方法,知足多種狀況.ui

步驟:委託方法,註冊執行url

1.代碼主體
 public class CensusdemoTask
    {
        System.Threading.Timer timer;
        private static int count = 1;

        public CensusdemoTask()
        {
            timer = new System.Threading.Timer(SetCensusURL, null, 0, 1000 * 60);
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public void SetCensusURL(object obj)
        { 
            string txt = string.Format("寫入時間:{0},次數{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), count);
            FileInfo f = new FileInfo("/124.txt");
            StreamWriter sw = File.Exists("/124.com") ? f.CreateText() : f.AppendText();
            byte[] txtbytes = Encoding.UTF8.GetBytes(txt);
            sw.WriteLine(txt);
            sw.Flush();
            sw.Close();
            count++;
        }
    }

 

2.註冊 Global.asax.csspa

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
           //註冊,
            BLL.SystemTask.CensusUrlTask t = new BLL.SystemTask.CensusUrlTask();
           
           WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
          
           // DependencyResolver.SetResolver(new NinjectDependencyResolver());
            //ControllerBuilder.Current.SetControllerFactory(new NinjectDependencyResolver());
        }
相關文章
相關標籤/搜索