c#中的Quartz

项目考虑到需要定时触发一些功能,想到了之前看到过的Quartz组件。

在vs中的Nuget中可以搜索到,官网有一些教程。

直接看一下如何使用:

 // 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()
                .WithSimpleSchedule(x => x
                    .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();</code></pre>

组件整体分为几个部分

  • Scheduler:可以认为是组建的框架
    • Scheduler在创建后一般就调用start开始运行,如果Scheduler没有开始,后面注册的Job是不会运行的
    • 使用完毕后调用Shutdown关闭
  • Job:代表实际执行的任务
    • 需要运行的代码继承IJob类,实现Execute接口
    • 注册给Scheduler时,通过IJobDetail创建与IJob关联的对象
  • Trigger:控制任务执行周期
    • 使用叫做fluent API的东西
    • 分为Simple和Cron两类
      • Simple类可以做简单的单次运行、或者每隔一段时间运行
      • Cron类基于一组空格分割的字符,可以进行更加灵活地配置。字符中依次代表: 
        • Seconds
        • Minutes
        • Hours
        • Day-of-Month
        • Month
        • Day-of-Week
        • Year (optional field)

基本需要了解的其实就是这些,高级一些的如配置文件,过期后的运行方式等,不太常使用。

另外在使用中发现,似乎log4net在其中打印不出来,还没有找到问题所在。。

更新:问题找到了,因为quartz和log4net都有同样的ILog和LogManager接口,代码自动添加的引用添加到了Common.Log上,导致没有走到log4net...

原文地址:https://www.cnblogs.com/mosakashaka/p/12608082.html