132

我想每 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();
    }
}
4

10 回答 10

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

var timer = new System.Threading.Timer((e) =>
{
    MyMethod();   
}, null, startTimeSpan, periodTimeSpan);
于 2012-10-22T20:39:09.433 回答
59

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

var timer = new System.Threading.Timer(
    e => MyMethod(),  
    null, 
    TimeSpan.Zero, 
    TimeSpan.FromMinutes(5));
于 2014-02-05T23:14:42.797 回答
11

在类的构造函数中启动一个计时器。间隔以毫秒为单位,因此 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();
}

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

static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    //YourCode
}
于 2015-12-10T14:40:05.260 回答
4

使用示例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("..."); 
}
于 2014-04-27T12:51:29.473 回答
4

我已经上传了一个 Nuget 包,它可以让它变得如此简单,你可以从这里ActionScheduler

它支持 .NET 标准 2.0

在这里如何开始使用它

using ActionScheduler;

var jobScheduler = new JobScheduler(TimeSpan.FromMinutes(8), new Action(() => {
  //What you want to execute
}));

jobScheduler.Start(); // To Start up the Scheduler

jobScheduler.Stop(); // To Stop Scheduler from Running.
于 2017-12-05T08:40:19.263 回答
3

使用Timer. 计时器文档

于 2012-10-22T20:38:56.497 回答
2

更新 .NET 6

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

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

while (await timer.WaitForNextTickAsync())
{
    //Business logic
}

这有几个优点,包括异步/等待支持,避免回调的内存泄漏,以及CancelationToken支持

延伸阅读

于 2022-01-28T01:47:45.663 回答
1

使用 DispatcherTimer:

 var _activeTimer = new DispatcherTimer {
   Interval = TimeSpan.FromMinutes(5)
 };
 _activeTimer.Tick += delegate (object sender, EventArgs e) { 
   YourMethod(); 
 };
 _activeTimer.Start();          
于 2020-11-22T18:12:45.980 回答
0

如果您需要更复杂的时间执行,例如 linux cron,可以使用 NCrontab。

我在生产中使用 NCrontab 很长时间了,效果很好!

努吉特

如何使用:

* * * * *
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)
using NCrontab;
//...

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
  // run every 5 minutes
  var schedule = CrontabSchedule.Parse("*/5 * * * *");
  var nextRun = schedule.GetNextOccurrence(DateTime.Now);
  logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);    
  do
  {
    if (DateTime.Now > nextRun)
    {
      logger.LogInformation("Sending notifications at: {time}", DateTimeOffset.Now);
      await DoSomethingAsync();
      nextRun = schedule.GetNextOccurrence(DateTime.Now);
    }
    await Task.Delay(1000, stoppingToken);
  } while (!stoppingToken.IsCancellationRequested);
}

如果需要,请添加秒数:

// run every 10 secs
var schedule = CrontabSchedule.Parse("0/10 * * * * *", new CrontabSchedule.ParseOptions { IncludingSeconds = true });
于 2021-11-22T13:59:37.243 回答
-1
while (true)
{
    Thread.Sleep(60 * 5 * 1000);
    Console.WriteLine("*** calling MyMethod *** ");
    MyMethod();
}
于 2012-10-22T20:39:04.840 回答