.NET 6.0 定时任务
时间: 2023-08-15 19:14:06 浏览: 63
.NET 6.0 引入了一个新的定时任务库,名为 `System.Threading.Timer`。这个库提供了一种简单的方式来在指定的时间间隔执行任务或者定时触发事件。
首先,你需要在你的代码中引入 `System.Threading` 命名空间。然后,你可以创建一个 `System.Threading.Timer` 实例,并指定一个回调函数和一个时间间隔。每次时间间隔到达时,回调函数都会被触发。
下面是一个使用 `System.Threading.Timer` 的示例代码:
```csharp
using System;
using System.Threading;
public class TimerExample
{
private static Timer _timer;
public static void Main()
{
// 创建一个 Timer 实例,指定回调函数和时间间隔
_timer = new Timer(TimerCallback, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
// 等待用户输入,避免程序过早退出
Console.ReadLine();
// 停止定时器
_timer.Dispose();
}
private static void TimerCallback(object state)
{
// 在这里编写你想要定期执行的任务代码
Console.WriteLine("Timer callback executed.");
}
}
```
在上面的示例中,`TimerCallback` 函数会每秒钟被调用一次,并打印一条消息到控制台。
请注意,在使用 `System.Threading.Timer` 时需要注意线程安全性,确保你的回调函数是线程安全的,或者采取适当的同步措施。
希望这能帮到你!如果有任何进一步的问题,请随时提问。