如何连续每40秒执行一次C#方法?
答案 0 :(得分:5)
您应该使用.net
中提供的定时器功能以下是来自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
}
}
答案 1 :(得分: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);
}
答案 2 :(得分: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();
}
答案 3 :(得分:0)
我建议使用Quartz.Net。您可以实现使用Quartz.Net计划的服务。您只需要按照自己的方式配置触发器。