MVC 定时执行任务

时间:2023-03-08 16:33:16

环境:.net4.5

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

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

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

1.代码主体
 public class CensusdemoTask
{
System.Threading.Timer timer;
private static int count = ; public CensusdemoTask()
{
timer = new System.Threading.Timer(SetCensusURL, null, , * );
}
[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());
}