1:安装依赖包
2:建立一个类Schedule继承Job
/// <summary>
/// 定时任务
/// </summary>
public class Schedule : Job
{
/// <summary>
/// 任务开始时间
/// </summary>
private const string _beginTime = "2021-09-27 00:00";
/// <summary>
/// 执行间隔,单位:毫秒(以任务开始时间为基准)
/// </summary>
private const int _interval = 1000 * 5;
/// <summary>
/// 是否需要等待上一次任务执行完毕后才可执行下一次任务
/// </summary>
private const bool _skipWhileExecuting = true;
[Invoke(Begin = _beginTime, Interval = _interval, SkipWhileExecuting = _skipWhileExecuting)]
public void Run()
{
Console.WriteLine("--------------------");
Console.WriteLine(DateTime.Now);
TaskA();
TaskB();
}
private void TaskA()
{
Console.WriteLine("任务A");
}
private void TaskB()
{
Console.WriteLine("任务B");
}
}
3:在Program.cs类中
builder.Services.AddTimedJob();
4:app.UseTimedJob();