标签:quartz入门
有段时间没写blog了,说来惭愧,最近一直在给公司做P2P项目的服务端,但这都不是借口,高尔基曾说过(不太确定T_T),时间就像海绵里的水,只要愿意挤总是有的!所以写博客的节奏还是必须脉动回来,必须养成不断学习,不断记录,不断总结的好习惯。废话不多说,最近需要做一些服务器端的定时任务,决定使用Quartz去实现,之前也没接触过,所以就边学边做了,顺便把这个过程记录下来。
首先看一下百科中对Quartz的简介:Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个,百个,甚至是好几万个Jobs这样复杂的程序。Jobs可以做成标准的Java组件或 EJBs。Quartz的最新版本为Quartz 2.2.1。
package com.test; import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class SimpleJob implements Job { @Override public void execute(JobExecutionContext jobCtx) throws JobExecutionException { // TODO Auto-generated method stub System.out.println("Triggered. Time is " + new Date()); } }
SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory(); Scheduler sched = schedFact.getScheduler(); sched.start();
// define the job and tie it to our HelloJob class JobDetail job = newJob(SimpleJob.class) .withIdentity("myJob", "group1") // name "myJob", group "group1" .build();
// Trigger the job to run now, and then every 40 seconds Trigger trigger = newTrigger() .withIdentity("myTrigger", "group1") .startNow() .withSchedule(simpleSchedule() .withIntervalInSeconds(5) .repeatForever()) .build();
// Tell quartz to schedule the job using our trigger sched.scheduleJob(job, trigger);
package com.test; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleScheduleBuilder; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; public class Test04 { public static void main(String[] args) { try { // Grab the Scheduler instance from the Factory Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.start(); // Job JobDetail job = JobBuilder.newJob(SimpleJob.class) .withIdentity("myTrigger", "group1").build(); // Trigger Trigger trigger = TriggerBuilder .newTrigger() .withIdentity("trigger1", "group1") .startNow() .withSchedule( SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(5).repeatForever()) .build(); scheduler.scheduleJob(job, trigger); } catch (SchedulerException se) { se.printStackTrace(); } } }
标签:quartz入门
原文地址:http://blog.csdn.net/wlwlwlwl015/article/details/44182777