我需要在定时器上调用函数(让我们说onTickTack()函数),并在ASP.NET MVC项目中重新加载一些信息.我知道有几种方法可以做到这一点,但是你认为最好的是哪一种?
注意:该函数只能从一个地方调用,每隔X分钟调用一次,直到应用程序启动.
编辑1:
重新加载一些信息 – 例如我在缓存中有一些东西,并且我想从定时器中的DB更新它 – 在一定时间内每天一次.
解决方法
这个问题的答案很大程度上取决于你在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 );
如果您的意思是别的话,请不要犹豫,为您的问题提供更多细节.