我想每隔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)
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)
Kyl*_*Mit 52
对于 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
支持
在您的类的构造函数中启动一个计时器。时间间隔以毫秒为单位,因此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)
使用示例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)
归档时间: |
|
查看次数: |
142308 次 |
最近记录: |