zoukankan      html  css  js  c++  java
  • Quartz.Net定时器

    一、Quartz.Net定时器

    1. Quartz.Net是一个定时任务框架,可以实现异常灵活的定时任务,开发人员只要编写少量的代码就可以实现“每隔1小时执行”、“每天22点执行”、“每月18日的下午执行8次”等各种定时任务。

    2. Quartz.Net中的概念:计划者(IScheduler)、工作(IJob)、触发器(Trigger)。给计划者一个工作,让他在Trigger(什么条件下做这件事)触发的条件下执行这个工作

    3. 将要定时执行的任务的代码写到实现IJob接口的Execute方法中即可,时间到来的时候Execute方法会被调用

    4. demo代码示例:首先需要引入Quartz.dll和common.logging.dll文件,先放置在lib文件夹中,建议在lib文件夹中新建一个子文件夹,这样能够更好的分辨。

    //每隔一段时间执行任务
    IScheduler sched;
     ISchedulerFactory sf = new StdSchedulerFactory();
                sched = sf.GetScheduler();  //计划者
                JobDetail job = new JobDetail("job1", "group1", typeof(IndexJob));//IndexJob为实现了IJob接口的类
                DateTime ts = TriggerUtils.GetNextGivenSecondDate(null, 5);//5秒后开始第一次运行
                TimeSpan interval =  TimeSpan.FromHours(1);//每隔1小时执行一次
     Trigger trigger = new SimpleTrigger("trigger1", "group1", "job1", "group1", ts, null,
                                             SimpleTrigger.RepeatIndefinitely, interval);//每若干小时运行一次,小时间隔由appsettings中的IndexIntervalHour参数指定
    
                sched.AddJob(job, true);
                sched.ScheduleJob(trigger);
                sched.Start();
    要关闭任务定时则需要sched.Shutdown(true)

     5. 新建一个 IndexJob类该类对应了上方的代码,会被定时执行。

    {
        /// <summary>
        /// 完成工作任务的定义。该类必须要实现 IJob接口
        /// </summary>
       public class IndexJob:IJob
        {
           /// <summary>
           /// 将明细表中的数据插入到汇总表中。
           /// </summary>
           /// <param name="context"></param>
           IBLL.IKeyWordsRankService bll = new BLL.KeyWordsRankService();
           public void Execute(JobExecutionContext context)
            {
                bll.DeleteAllKeyWordsRank();
                bll.InsertKeyWordsRank();
            }
        }
    }
  • 相关阅读:
    6. Flask请求和响应
    5. Flask模板
    FW:Software Testing
    What is the difference between modified duration, effective duration and duration?
    How to push master to QA branch in GIT
    FTPS Firewall
    Query performance optimization of Vertica
    (Forward)5 Public Speaking Tips That'll Prepare You for Any Interview
    (转)The remote certificate is invalid according to the validation procedure
    Change
  • 原文地址:https://www.cnblogs.com/wangjinya/p/10755168.html
Copyright © 2011-2022 走看看