QuartZ
1.nuget:引用QuartZ
2.
public async static Task Init()
{
/// 创建单元载体
StdSchedulerFactory factory = new StdSchedulerFactory();
IScheduler scheduler = await factory.GetScheduler();
await scheduler.Start();
//Job(作业)
IJobDetail jobDetail = JobBuilder.Create()
.WithIdentity("SendMessageJob", "gourp1")
.WithDescription("this is send message job")
.Build();
jobDetail.JobDataMap.Add("K1", "axin1"); //传入参数
jobDetail.JobDataMap.Add("K2", "axin2");
jobDetail.JobDataMap.Add("K3", "axin3");
//Trigger(时间策略)
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("sendMessageTrigger", "group1")
//.StartNow()
.WithSimpleSchedule(w => w.WithIntervalInSeconds(5).WithRepeatCount(300))
.Build();
trigger.JobDataMap.Add("K4", "axin4"); //传入参数
//把时间策略和作业承载到单元上
await scheduler.ScheduleJob(jobDetail, trigger);
}
}
3.
public class SendMessageJob : IJob
{
///
/// task 内部就是要执行的任务
///
///
///
///
public async Task Execute(IJobExecutionContext context)
{
//throw new NotImplementedException();
await Task.Run(() =>
{
//Console.WriteLine("任务开始");
//Console.WriteLine("任务开始");
//Console.WriteLine("任务开始");
//Console.WriteLine("任务开始");
//Console.WriteLine("任务开始");
string str = context.JobDetail.JobDataMap.GetString("K1"); //接受参数
string str2 = context.Trigger.JobDataMap.GetString("K4"); //接受参数
Console.WriteLine(str);
Console.WriteLine(str2);
});
}
}
4.
public class Program
{
static void Main(string[] args)
{
try
{
Manager.Init().GetAwaiter().GetResult();
Console.ReadLine();
}
catch (Exception)
{
throw;
}
}
}