如何在计时器ASP.NET MVC上调用函数

我需要调用timer上的函数(比如onTickTack()函数)并在ASP.NET MVC项目中重新加载一些信息。 我知道有几种方法可以做到这一点,但你认为哪一种最好?

注意:该函数应该只从一个地方调用,每隔X分钟调用一次,直到应用程序启动。

编辑1:重新加载一些信息 – 例如我在缓存中有一些东西,我想在计时器上更新它 – 在某个时间每天一次。

这个问题的答案很大程度上取决于你在ASP.NET MVC项目中重新加载一些信息是什么意思。 这不是一个明确陈述的问题,因此,显然,它不能有明确的答案。

因此,如果我们假设您希望定期轮询某些控制器操作并更新视图上的信息,则可以使用setInterval javascript函数通过发送AJAX请求并更新UI来定期轮询服务器:

window.setInterval(function() { // Send an AJAX request every 5s to poll for changes and update the UI // example with jquery: $.get('/foo', function(result) { // TODO: use the results returned from your controller action // to update the UI }); }, 5000); 

另一方面,如果您定期在服务器上执行某项任务,则可以使用RegisterWaitForSingleObject方法,如下所示:

 var waitHandle = new AutoResetEvent(false); ThreadPool.RegisterWaitForSingleObject( waitHandle, // Method to execute (state, timeout) => { // TODO: implement the functionality you want to be executed // on every 5 seconds here // Important Remark: This method runs on a worker thread drawn // from the thread pool which is also used to service requests // so make sure that this method returns as fast as possible or // you will be jeopardizing worker threads which could be catastrophic // in a web application. Make sure you don't sleep here and if you were // to perform some I/O intensive operation make sure you use asynchronous // API and IO completion ports for increased scalability }, // optional state object to pass to the method null, // Execute the method after 5 seconds TimeSpan.FromSeconds(5), // Set this to false to execute it repeatedly every 5 seconds false ); 

如果您的意思是其他内容,请不要犹豫,为您的问题提供更多详细信息。

您可以在Gllo.asax的OnApplicationStart事件中使用Timer类…

 public static System.Timers.Timer timer = new System.Timers.Timer(60000); // This will raise the event every one minute. . . . timer.Enabled = true; timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); . . . static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { // Do Your Stuff } 

我的解决方案是这样的;

  

叫方法;

 [HttpPost] public ActionResult Method() { return Json("Tick"); } 

我这样做是通过从Application_Start()启动一个工作线程。

这是我的class级:

 public interface IWorker { void DoWork(object anObject); } public enum WorkerState { Starting = 0, Started, Stopping, Stopped, Faulted } public class Worker : IWorker { public WorkerState State { get; set; } public virtual void DoWork(object anObject) { while (!_shouldStop) { // Do some work Thread.Sleep(5000); } // thread is stopping // Do some final work } public void RequestStop() { State = WorkerState.Stopping; _shouldStop = true; } // Volatile is used as hint to the compiler that this data // member will be accessed by multiple threads. protected volatile bool _shouldStop; } 

它是这样开始的:

  var backgroundThread = new Thread(Worker.DoWork) { IsBackground = true, Name = "MyThread" }; backgroundThread.Start();