天天看點

C# Quartz.Net的使用

using System;
using System.Threading.Tasks;
using Demo.Services;
using Quartz;

namespace Demo.QuartzJob
{
    public class MyJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            return Task.Factory.StartNew(() => { FrameWorkInfoService.CheckFromGithub(); });
        }
    }
}

           
using System;
using Demo.QuartzJob;
using Quartz;
using Quartz.Impl;

namespace Demo.Services
{
    public static class QuartzService
    {
        public async static void InitQuartz()
        {
            var scheduler = await new StdSchedulerFactory().GetScheduler();
            await scheduler.Start();

            Console.WriteLine("任務排程器已啟動");

            //添加排程
            await scheduler.ScheduleJob(
                JobBuilder.Create<MyJob>() // 指定job
                    .Build(),
                TriggerBuilder.Create()
                    .WithCronSchedule("0 0 1 * * ?") //每天淩晨1點執行
                    .Build());
        }
    }
}

           
using System;
using System.Threading.Tasks;
using Demo.Services;
using Microsoft.Extensions.Hosting;

namespace Demo
{
    internal static class Program
    {
        public async static Task Main(string[] args)
        {        
            QuartzService.InitQuartz();  // 調用

            // 監聽 Ctrl + C
            await new HostBuilder().RunConsoleAsync();
        }
    }
}