-1

如何每 40 秒连续执行一个 C# 方法?

4

4 回答 4

5

您应该使用 .net 中提供的 Timer 功能

文档

这是来自 MSDN 的代码,略有改动。

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {

        // Create a timer with a fourty second interval.
        aTimer = new System.Timers.Timer(40000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);    


        // If the timer is declared in a long-running method, use 
        // KeepAlive to prevent garbage collection from occurring 
        // before the method ends. 
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is  
    // raised. 
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        //Code that needs repeating every fourty seconds
    }
}
于 2013-08-08T10:09:50.010 回答
2

看看 System.Threading.Timer

var timer = new System.Threading.Timer(new TimerCallback(YourMethod), null, 40000, Timeout.Infinite);
private void YourMethod(object state)
{
    //Magic
    timer.Change(40000, Timeout.Infinite);
}
于 2013-08-08T10:12:09.327 回答
1

尝试这个

<asp:UpdatePanel runat="server" UpdateMode="Always">
    <ContentTemplate>
    <asp:Timer  ID="timer" runat="server" Interval="40000"></asp:Timer>
    </ContentTemplate>
</asp:UpdatePanel>

在后面的代码中

    protected void Page_Load(object sender, EventArgs e)
    {
       callyourfunction();
     }
于 2013-08-08T10:14:29.940 回答
0

我可以建议为此使用 Quartz.Net。您可以实现使用 Quartz.Net 安排的服务。您只需要按照您想要的方式配置您的触发器。

于 2015-09-08T01:15:34.817 回答