2010-11-03 quartz学习笔记一

Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that are programmed to fulfill the requirements of your application. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering. You can download the most recent stable version at  http://quartz-scheduler.org/overview/index.html.

      Quartz是一个开源的任务调度服务,可以同时运行成百上千个简单或者复杂的任务。

一.搭建Quart运行环境

    下载最新版本,解压后将lib目录下所有jar包加入你工程classpath下,注意jar包的冲突问题。将跟目录下的quartz-all-***.jar加入classpath,其中xxx为版本号。

二.最简单的helloWorld

   (1) 引入所需要的类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;

   (2)获取一个Scheduler

 // 使用工厂模式
SchedulerFactory sf = new StdSchedulerFactory(); 
Scheduler sched = sf.getScheduler();

  (3) 声明一个任务和1个触发器

 

        // computer a time that is on the next round minute
        Date runTime = TriggerUtils.getEvenMinuteDate(new Date());
        // define the job and tie it to our HelloJob class
        JobDetail job = new JobDetail("job1", "group1", HelloJob.class);
        // Trigger the job to run on the next round minute
        SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1", runTime);

 (4)将任务和触发器进行关联

 

   // Tell quartz to schedule the job using our trigger 
 sched.scheduleJob(job, trigger);

 (5)启动调度器

 

       // Start up the scheduler (nothing can actually run until the 
        // scheduler has been started)
        sched.start();

 (6)执行完任务后关闭调度器

 

     // shut down the scheduler
    /// 如果不关闭调度器,则程序会一直执行下去,因为一直有个调度器的线程在执行
        log.info("------- Shutting Down ---------------------");
        sched.shutdown(true);
        log.info("------- Shutdown Complete -----------------");

 (7)自定义的任务类HelloJob

 

public class HelloJob implements Job 

 (8)实现Excute方法

 

   public void execute(JobExecutionContext context)
        throws JobExecutionException {

        // Say Hello to the World and display the date/time
        System.out.println("Hello World! - " + new Date());
    }

 (9)执行结果

 

Hello World! - Wed Nov 03 11:40:00 CST 2010
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值