每x分钟调用一次方法


116

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

10
System.Threading.Timer
user703016 2012年

1
或System.Timers.Timer-dotnetperls.com/timer – sinanakyazici 2012
20:39

Answers:


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

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

25
设置时间间隔的另一种方法是传递时间跨度对象。我认为这会更清洁:Timespan.FromMinutes(5)
Michael Haren

2
@MichaelHaren我不知道,那很好。谢谢!
asawyer 2012年

4
@asawyer不幸的是,您的实现给出了编译错误。TotalMilliseconds当计时器需要整数或时,返回一个double值TimeSpan。我试图将您的答案更新为雇用TimeSpan并抛出不必要的膨胀的答案;但是,您还原了它。
安德烈C.安德森

2
@AndréChristofferAndersen将“时间”构造函数中的0更改为TimeSpan.Zero。代码在此之后起作用。
RredCat 2015年

2
代码给出错误。这是新的修复System.Threading.Timer((e)=> {Func();},null,TimeSpan.Zero,TimeSpan.FromMinutes(1).TotalMilliseconds);
亚势

54

我基于@asawyer的答案。他似乎没有出现编译错误,但是我们中有些人知道。这是Visual Studio 2010中的C#编译器将接受的版本。

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

12
后代评论。当您Dispose()在计时器对象上调用method 时,它将停止。示例: timer.Dispose()使用上面的代码作为参考。但是,这将破坏计时器,并阻止您再次使用它。timer.Change(Timeout.Infinite, Timeout.Infinite)如果您想在同一程序中再次使用计时器,效果会更好。
乔尔·特劳格

1
但是,当我在控制台应用程序中运行MyMethod()时为什么无法运行
Izuagbala

@Izuagbala在不知道如何设置的情况下,很难说为什么它对您不起作用。该解决方案已在控制台应用程序中进行了测试。
安德烈·C·安徒生

空是什么?
丹尼尔·雷哈尼安

@DanielReyhanian您可以添加对象状态而不是null,这是在调用回调函数时作为参数(即第一个参数)。
安德烈·C·安徒生

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

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

static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    //YourCode
}

4

我已经上传了NuGet包,可以使如此简单,你可以从这里有它ActionScheduler

它支持.NET Standard 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.

无法安装软件包“ CrystalJobScheduler 1.0.0”。您正在尝试将此软件包安装到以'.NETFramework,Version = v4.5'为目标的项目中,但是该软件包不包含任何与该框架兼容的程序集引用或内容文件。有关更多信息,请与软件包作者联系。
Aditya Bokade '19

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("..."); 
}


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.