查看完整版本: java计划任务:Quartz

大饼先生 2008-5-26 09:36

java计划任务:Quartz

What is Quartz?Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE 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 or EJBs. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.


If your application has tasks that need to occur at given moments in time, or if your system has recurring maintenance jobs then Quartz may be your ideal solution.
Sample uses of job scheduling with Quartz:
[list][*]Driving Workflow: As a new order is initially placed, schedule a Job to fire in exactly 2 hours, that will check the status of that order, and trigger a warning notification if an order confirmation message has not yet been received for the order, as well as changing the order's status to 'awaiting intervention'.[*]System Maintenance: Schedule a job to dump the contents of a database into an XML file every business day (all weekdays except holidays) at 11:30 PM.[/list]

A simple Quartz Test: Say hello using Quartz:

HelloJob.java
[code]
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job{
public static Log log = LogFactory.getLog(HelloJob.class);

public void execute(JobExecutionContext arg0) throws JobExecutionException {
  log.info("Hello~" + new Date());
}
}[/code]

SimpleQuartz.java
[code]
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;
public class SimpleQuartz {
  public void run() throws Exception {
         Log log = LogFactory.getLog(SampleQuartz.class);
         log.info("------- Initializing ----------------------");
         // First we must get a reference to a scheduler
         SchedulerFactory sf = new StdSchedulerFactory();
         Scheduler sched = sf.getScheduler();
         log.info("------- Initialization Complete -----------");
         log.info("------- Scheduling Jobs -------------------");
         // 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);
         
         // Tell quartz to schedule the job using our trigger
         sched.scheduleJob(job, trigger);
         log.info(job.getFullName() + " will run at: " + runTime);  
         // Start up the scheduler (nothing can actually run until the
         // scheduler has been started)
         sched.start();
         log.info("------- Started Scheduler -----------------");
         // wait long enough so that the scheduler as an opportunity to
         // run the job!
         log.info("------- Waiting 90 seconds... -------------");
         try {
             // wait 90 seconds to show jobs
             Thread.sleep(90L * 1000L);
             // executing...
         } catch (Exception e) {
         }
         // shut down the scheduler
         log.info("------- Shutting Down ---------------------");
         sched.shutdown(true);
         log.info("------- Shutdown Complete -----------------");
     }
     public static void main(String[] args) throws Exception {
         SampleQuartz example = new SampleQuartz();
         example.run();
     }
}

[/code]

大饼先生 2008-5-26 09:52

在Quartz中,一个完整的计划任务分为“任务”和“触发器”,任务即程序要实现的内容。而触发器标志着什么时候什么情况下任务将运行。

定义一个“任务”只要实现org.quartz.Job接口,即实现一个
public void execute(JobExecutionContext arg0) throws JobExecutionException
在这个方法体里具体内容将在任务被触发时自动调用。其参数JobExecutionContext故名思义,即“任务上下文”,让任务知道自己的运行上下文。比如说任务名称等等(参考API文档)

触发器(偷下懒,直接从文档里COPY出来)
Trigger objects are used to trigger the execution (or 'firing') of jobs. When you wish to schedule a job, you instantiate a trigger and 'tune' its properties to provide the scheduling you wish to have. Triggers may also have a JobDataMap associated with them - this is useful to passing parameters to a Job that are specific to the firings of the trigger. Quartz ships with a handful of different trigger types, but the most commonly used types are SimpleTrigger and CronTrigger.
SimpleTrigger is handy if you need 'one-shot' execution (just single execution of a job at a given moment in time), or if you need to fire a job at a given time, and have it repeat N times, with a delay of T between executions. CronTrigger is useful if you wish to have triggering based on calendar-like schedules - such as "every Friday, at noon" or "at 10:15 on the 10th day of every month."

上面的例子中,定义了一个SimpleTigger:
SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1", runTime);
API里SimpleTigger有好几种构造函数。上面的构造函数说明如下:
SimpleTrigger(String name, String group, Date startTime)
           Create a SimpleTrigger that will occur at the given time, and not repeat.


定义好任务和触发器后,只要分配任务就行了:

Scheduler sched = new StdSchedulerFactory().getScheduler();
sched.scheduleJob(job, trigger);
sched.start();

[[i] 本帖最后由 大饼先生 于 2008-5-26 09:55 编辑 [/i]]

大饼先生 2008-5-28 09:02

Quartz Job Scheduling Framework
很不错的一本来,共享给兄弟们~~
页: [1]
查看完整版本: java计划任务:Quartz