每x分钟调用一次方法

use*_*862 103 c#

我想每隔5分钟调用一些方法.我怎样才能做到这一点?

public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("*** calling MyMethod *** ");
        Console.ReadLine();
    }

    private MyMethod()
    {
        Console.WriteLine("*** Method is executed at {0} ***", DateTime.Now);
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

asa*_*yer 160

var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);

var timer = new System.Threading.Timer((e) =>
{
    MyMethod();   
}, null, startTimeSpan, periodTimeSpan);
Run Code Online (Sandbox Code Playgroud)

  • 设置间隔的另一种方法是传入一个timepan对象.我认为它有点清洁:[`Timespan.FromMinutes(5)`](http://msdn.microsoft.com/en-us/library/system.timespan.fromminutes.aspx) (23认同)
  • @asawyer不幸的是你的实现会产生编译错误.`TotalMilliseconds`返回一个double,而计时器需要整数或'TimeSpan`.我试图将你的答案更新为使用"TimeSpan"的答案并抛出不必要的膨胀; 但是,你还原了它. (4认同)
  • @MichaelHaren我不知道,那很好.谢谢! (2认同)
  • @AndréChristofferAndersen将Time构造函数中的0更改为TimeSpan.Zero.代码在此之后工作. (2认同)
  • 代码给出了错误.这是修复新的System.Threading.Timer((e)=> {Func();},null,TimeSpan.Zero,TimeSpan.FromMinutes(1).TotalMilliseconds); (2认同)

And*_*sen 54

我的基础是@ asawyer的回答.他似乎没有得到编译错误,但我们中的一些人做了.这是Visual Studio 2010中的C#编译器将接受的版本.

var timer = new System.Threading.Timer(
    e => MyMethod(),  
    null, 
    TimeSpan.Zero, 
    TimeSpan.FromMinutes(5));
Run Code Online (Sandbox Code Playgroud)

  • 评论后代.当你在timer对象上调用`Dispose()`方法时它会停止.示例:`timer.Dispose()`使用上面的代码作为参考.这会破坏计时器,但会阻止您再次使用它.如果你想在同一个程序中再次使用计时器,`timer.Change(Timeout.Infinite,Timeout.Infinite)`会更好. (11认同)
  • 怎么阻止这个? (4认同)

Kyl*_*Mit 52

更新.NET 6

对于 dotnet 6+ 中的大多数用例,您应该使用PeriodicTimer

var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));

while (await timer.WaitForNextTickAsync())
{
    //Business logic
}
Run Code Online (Sandbox Code Playgroud)

这有几个优点,包括 async/await 支持、避免回调造成的内存泄漏以及CancelationToken支持

进一步阅读


Mai*_*gma 7

在您的类的构造函数中启动一个计时器。时间间隔以毫秒为单位,因此5 * 60秒= 300秒= 300000毫秒。

static void Main(string[] args)
{
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Interval = 300000;
    timer.Elapsed += timer_Elapsed;
    timer.Start();
}
Run Code Online (Sandbox Code Playgroud)

然后调用GetData()timer_Elapsed这样的事件:

static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    //YourCode
}
Run Code Online (Sandbox Code Playgroud)


PJ3*_*PJ3 5

使用示例Timer

using System;
using System.Timers;

static void Main(string[] args)
{
    Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
    t.AutoReset = true;
    t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
    t.Start();
}

// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("..."); 
}
Run Code Online (Sandbox Code Playgroud)