gpt4 book ai didi

c# - 如何在 ASP.NET MVC 定时器上调用函数

转载 作者:行者123 更新时间:2023-12-02 19:17:32 25 4
gpt4 key购买 nike

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

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

编辑1:重新加载一些信息 - 例如,我在缓存中有一些信息,我想在计时器上从数据库更新它 - 每天在特定时间更新一次。

最佳答案

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

因此,如果我们假设您希望定期轮询某些 Controller 操作并更新 View 上的信息,您可以使用 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
);

如果您有其他意思,请随时提供有关您问题的更多详细信息。

关于c# - 如何在 ASP.NET MVC 定时器上调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4329859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com