• MVC 定时执行任务


    环境:.net4.5

    需求:需要一个方法定时执行任务

    解决: System.Threading.Timer 提供以指定的时间间隔执行方法的机制。 此类不能被继承,有10多种实例化方法,满足多种情况.

    步骤:委托方法,注册执行

    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.txt") ? f.CreateText() : f.AppendText();
                byte[] txtbytes = Encoding.UTF8.GetBytes(txt);
                sw.WriteLine(txt);
                sw.Flush();
                sw.Close();
                count++;
            }
        }

    2.注册 Global.asax.cs

     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());
            }
  • 相关阅读:
    堆栈详解
    结构体内存对齐
    const限定符
    硬盘及其分区(0819整理)
    Android编译环境搭建(0818-0819)
    wordpress导入模板数据
    git新建仓库
    android 镜像源
    js 获取浏览器可视窗口大小,滚动条高度
    jquery 获取浏览器可视窗口大小,滚动条高度
  • 原文地址:https://www.cnblogs.com/Fyhong/p/3594150.html
Copyright © 2020-2023  润新知