C#定时执行程序

本文介绍了如何在C#应用程序中利用Global.asax文件设置定时执行任务的方法,通过示例代码展示具体的实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Global.asax中写入以下代码:

  protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //需要循环定时执行的程序
            AddCount(null, null);//需要立即执行
            System.Timers.Timer timer = new System.Timers.Timer(600000);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(AddCount); //AddCount是一个方法,此方法就是每个6分钟而做的事情
            timer.AutoReset = true;
            //给Application["timer"]一个初始值
            Application.Lock();
            Application["timer"] = 1;
            Application.UnLock();
            timer.Enabled = true;
        }
        private void AddCount(object sender, ElapsedEventArgs e)
        {
            Applicatio