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

时间:2010-12-01 22:36:31

标签: c# asp.net asp.net-mvc asp.net-mvc-2 asp.net-ajax

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

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

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

4 个答案:

答案 0 :(得分:26)

这个问题的答案在很大程度上取决于在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
);

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

答案 1 :(得分:12)

您可以在Global.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
}

答案 2 :(得分:2)

我的解决方案是这样的;

<script type="text/javascript">
    setInterval(
        function ()
        {
            $.post("@Url.Action("Method", "Home")", {}, function (data) {
                alert(data);
            });
        }, 5000)
</script>

被叫方法;

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

答案 3 :(得分:1)

我是通过从Application_Start()启动一个工作线程来完成的。

这是我的班级:

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();