在控制台应用中实现一个计划任务
csharp
static System.Timers.Timer timer;
public static void Main()
{
var services = new ServiceCollection();
ConfigureServices(services);
// 创建ServiceProvider
var serviceProvider = services.BuildServiceProvider();
// app程序运行入口
await serviceProvider.GetService<App>().Run(args);
}
public static void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<MyJob>();
}
//打开计划任务
public class App
{
MyJob job;
public App(MyJob job)
{
this.job=job;
job.Start(10);
}
}
//计划任务
public class MyJob
{
System.Timers.Timer timer;
public MyJob()
{
timer = new System.Timers.Timer(Interval);
timer.AutoReset = true;
}
public void Start(int second)
{
Interval = second*1000;
timer.Interval=Interval;
timer.Enabled = true;
timer.AutoReset = true;
}
public void Stop()
{
timer.Enabled = false;
timer.AutoReset = false;
}
int Interval { get; set; } = 5000;
private void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine(e.SignalTime.ToString());
}
}
在asp.net应用中实现一个计划任务
自定义一个任务类MyMob.cs,继承BackgroundService
实现ExecuteAsync()
启动定时器
注册计划任务
csharpbuilder.Services.AddHostedService<MyMob>();
计划任务实例代码
csharp
public class MyJob : BackgroundService
{
//每隔5秒执行一次
System.Timers.Timer timer = new System.Timers.Timer(5000);
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
return Task.CompletedTask;
var timer = new System.Timers.Timer(5000);
timer.Enabled = true;
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = true;
//timer.Enbled=false;//暂停计时器
//timer.Interval=2000;//改变时间间隔为2秒
return Task.CompletedTask;
}
private void Timer_Elapsed(object? sender, ElapsedEventArgs e)
{
//任务内容
Console.WriteLine(e.SignalTime.ToString());
}
}
//注册服务
builder.Services.AddHostedService<MyMob>();