asp.net或者MVC定时自动执行某操作

using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;

namespace SystemTask
{
    public class CensusdemoTask
    {
        System.Threading.Timer timer;
        private static int count = 1;

        public CensusdemoTask()
        {
            //3秒执行一次
            timer = new System.Threading.Timer(SetCensusURL, null, 0, 1000 * 3);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public void SetCensusURL(object obj)
        {
            var date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string txt = string.Empty;
            if (count==1)
            {
                txt += string.Format("========系统重启========\r\n");
            }
            txt += string.Format("写入时间:{0},次数{1}", date, count);
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                string path = "D:\\1.txt";//文件的路径,保证文件存在。
                fs = new FileStream(path, FileMode.Append);
                sw = new StreamWriter(fs);
                sw.WriteLine(txt);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                sw.Dispose();
                sw.Close();
                fs.Dispose();
                fs.Close();
            }
            count++;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Routing;

namespace Mvc
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //在Global.asax的Application_Start中注册任务
            SystemTask.CensusdemoTask t = new SystemTask.CensusdemoTask();
        }
    }
}


posted @ 2016-12-16 20:04  深南大道  阅读(397)  评论(0编辑  收藏  举报