public partial class SystemScheduler
{
private SystemScheduler()
{
}
public static SystemScheduler CreateInstance()
{
return new SystemScheduler();
}
private IScheduler _scheduler;
public async Task RunQuartz()
{
try
{
//这里读取配置文件中的任务开始时间
int hour = int.Parse(ConfigurationManager.AppSettings["Hour"]);
int minute = int.Parse(ConfigurationManager.AppSettings["Minute"]);
// Grab the Scheduler instance from the Factory
NameValueCollection props = new NameValueCollection
{
{ "quartz.serializer.type", "binary" }
};
StdSchedulerFactory factory = new StdSchedulerFactory(props);
IScheduler scheduler = await factory.GetScheduler();
// and start it off
await scheduler.Start();
// define the job and tie it to our HelloJob class
IJobDetail job = JobBuilder.Create<HelloJob>()
.WithIdentity("job1", "group1")
.Build();
// Trigger the job to run now, and then repeat every 10 seconds
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
//.StartNow()
.StartAt(DateBuilder.DateOf(hour, minute, 0))
.WithSimpleSchedule(x => x
.WithIntervalInHours(24)
//.WithIntervalInSeconds(10)
.RepeatForever())
.Build();
// Tell quartz to schedule the job using our trigger
await scheduler.ScheduleJob(job, trigger);
// some sleep to show what's happening
await Task.Delay(TimeSpan.FromSeconds(60));
// and last shut down the scheduler when you are ready to close your program
await scheduler.Shutdown();
}
catch (SchedulerException se)
{
}
}
public class HelloJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
//using (StreamWriter sw = File.AppendText(@"E:SchedulerService.txt"))
//{
// sw.WriteLine("------------------" + "HelloJob:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 执行了一次任务" + "------------------");
// sw.Flush();
// //await Console.Out.WriteLineAsync("Greetings from HelloJob!");
//}
await Console.Out.WriteLineAsync("Greetings from HelloJob!");
}
}
}