• 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();
            }
        }
    }
  • 相关阅读:
    搭建WAP应用开发环境
    How To Recover Openfire admin Password
    Domino分区服务器的安装与设置
    apache安全加固
    apache的web文件根目录
    iis绑定域名
    dedecms出现Error: Errno:0 SQL::错误解决方法
    加入收藏兼容ie和火狐
    phpcms毛遂
    .htaccess文件
  • 原文地址:https://www.cnblogs.com/wangjinya/p/10755168.html
Copyright © 2020-2023  润新知