创建简易控制台定时任务
- 创建winform的可以看:https://blog.csdn.net/wayhb/article/details/134279205
步骤
- 创建控制台程序
- 使用vs2019
- 新建项目,控制台程序,使用
.net4.7.2
- 项目右键(管理NuGet程序包),搜索Quartz,安装
![使用C#插件Quartz.Net定时执行CMD任务工具2_第1张图片](http://img.e-com-net.com/image/info8/61255d5522984251bd1c0af445fcf11c.jpg)
- 使用Quartz.Net官网示例运行程序
- 打开官网
https://www.quartz-scheduler.net/documentation/quartz-3.x/quick-start.html#trying-out-the-application
,在程序入库Program.cs粘贴官网示例
using Quartz;
using Quartz.Impl;
using Quartz.Logging;
using System;
using System.Threading.Tasks;
namespace ConsoleSkWork
{
class Program
{
private static async Task Main(string[] args)
{
LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
StdSchedulerFactory factory = new StdSchedulerFactory();
IScheduler scheduler = await factory.GetScheduler();
await scheduler.Start();
IJobDetail job = JobBuilder.Create<HelloJob>()
.WithIdentity("job1", "group1")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(10)
.RepeatForever())
.Build();
await scheduler.ScheduleJob(job, trigger);
await Task.Delay(TimeSpan.FromSeconds(60));
await scheduler.Shutdown();
Console.WriteLine("Press any key to close the application");
Console.ReadKey();
}
private class ConsoleLogProvider : ILogProvider
{
public Logger GetLogger(string name)
{
return (level, func, exception, parameters) =>
{
if (level >= LogLevel.Info && func != null)
{
Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + level + "] " + func(), parameters);
}
return true;
};
}
public IDisposable OpenNestedContext(string message)
{
throw new NotImplementedException();
}
public IDisposable OpenMappedContext(string key, object value, bool destructure = false)
{
throw new NotImplementedException();
}
}
}
public class HelloJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
await Console.Out.WriteLineAsync("Greetings from HelloJob!");
}
}
}
- 运行控制台程序
![使用C#插件Quartz.Net定时执行CMD任务工具2_第2张图片](http://img.e-com-net.com/image/info8/a6d82d1c47df48e9895d93ae32c854cd.jpg)
说明:
info是日志插件输出的
hellojob就是任务触发的
- 添加触发监听器
- 触发监听器是用于监听触发器的
- 添加触发监听器可以在任务执行前后执行其他动作,例如输出下一次该任务执行时间
- 触发监听器官网解释:https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/trigger-and-job-listeners.html
- 继承触发监听器接口有4个方法需要实现
public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
{}
public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
{}
public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default)
{}
public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default)
{}
scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener());
完整程序
using System;
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;
using Quartz.Logging;
namespace ConsoleApp1
{
public class Program
{
private static async Task Main(string[] args)
{
LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
StdSchedulerFactory factory = new StdSchedulerFactory();
IScheduler scheduler = await factory.GetScheduler();
await scheduler.Start();
IJobDetail job = JobBuilder.Create<HelloJob>()
.WithIdentity("job1", "group1")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(10)
.RepeatForever())
.Build();
scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener());
await scheduler.ScheduleJob(job, trigger);
await Task.Delay(TimeSpan.FromSeconds(60));
await scheduler.Shutdown();
Console.WriteLine("Press any key to close the application");
Console.ReadKey();
}
private class ConsoleLogProvider : ILogProvider
{
public Logger GetLogger(string name)
{
return (level, func, exception, parameters) =>
{
if (level >= LogLevel.Info && func != null)
{
Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + level + "] " + func(), parameters);
}
return true;
};
}
public IDisposable OpenNestedContext(string message)
{
throw new NotImplementedException();
}
public IDisposable OpenMappedContext(string key, object value, bool destructure = false)
{
throw new NotImplementedException();
}
}
}
public class HelloJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
DateTime currentDateTime = DateTime.UtcNow;
await Console.Out.WriteLineAsync("当前日期和时间:" + currentDateTime.AddHours(8));
}
}
}
using Quartz;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class CustomTriggerListener : ITriggerListener
{
public string Name => "CustomTriggerListener";
public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
{
Console.WriteLine("【*********************************************】");
Console.WriteLine($"【{Name}】---【TriggerFired】-【触发】");
await Task.CompletedTask;
}
public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
{
Console.WriteLine($"【{Name}】---【VetoJobExecution】-【判断作业是否继续】-{true}");
return await Task.FromResult(cancellationToken.IsCancellationRequested);
}
public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default)
{
Console.WriteLine($"【{Name}】---【TriggerComplete】-【触发完成】");
DateTimeOffset dd = (DateTimeOffset)trigger.GetNextFireTimeUtc();
Console.WriteLine("【下次执行时间:】"+dd.DateTime.AddHours(8));
await Task.CompletedTask;
}
public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default)
{
Console.WriteLine($"【{Name}】---【TriggerMisfired】【触发作业】");
await Task.CompletedTask;
}
}
}