quartz 订阅
Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个,百个,甚至是好几万个Jobs这样复杂的程序。Jobs可以做成标准的Java组件或 EJBs。Quartz的最新版本为Quartz 2.3.2。 展开全文
Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个,百个,甚至是好几万个Jobs这样复杂的程序。Jobs可以做成标准的Java组件或 EJBs。Quartz的最新版本为Quartz 2.3.2。
信息
外文名
quartz
最新版本
Quartz 2.3.2
类    别
开源项目
中文名
扩特兹公式
解    释
由java编写的开源作业调度框架
quartz调度简单
Quartz是一个完全由java编写的开源作业调度框架。不要让作业调度这个术语吓着你。尽管Quartz框架整合了许多额外功能, 但就其简易形式看,你会发现它易用得简直让人受不了!简单地创建一个实现org.quartz.Job接口的java类。Job接口包含唯一的方法:public void execute(JobExecutionContext context)throws JobExecutionException;在你的Job接口实现类里面,添加一些逻辑到execute()方法。一旦你配置好Job实现类并设定好调度时间表,Quartz将密切注意剩余时间。当调度程序确定该是通知你的作业的时候,Quartz框架将调用你Job实现类(作业类)上的execute()方法并允许做它该做的事情。无需报告任何东西给调度器或调用任何特定的东西。仅仅执行任务和结束任务即可。如果配置你的作业在随后再次被调用,Quartz框架将在恰当的时间再次调用它。
收起全文
精华内容
下载资源
问答
  • Quartz

    千次阅读 2017-12-06 09:11:27
    这里以quartz-2.2.3为例 1.上官网下载quartz的完整版,quartz-2.2.3-distribution.tar,里面包含源代码,官方Demo,Java Doc,所需的Jar包,JDBCStore数据库等文件,下载完毕,将lib文件下的jar包复制到项目中 2....

    这里以quartz-2.2.3为例

    1.上官网下载quartz的完整版,quartz-2.2.3-distribution.tar,里面包含源代码,官方Demo,Java Doc,所需的Jar包,JDBCStore数据库等文件,下载完毕,将lib文件下的jar包复制到项目中

    2.quartz主要有三个概念

    (1)任务调度器Scheduler 

    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    Scheduler schedule = StdSchedulerFactory.getDefaultScheduler();

    (2)任务触发器Trigger

    Trigger tri = TriggerBuilder.newTrigger().build;

    (3)任务Job

    JobBuilder.newJob(MyJob.class).build();


    其他:

    Cron表达式:
    格式:秒 分 时 日 月  星期几 年(可选)
    1:?只能用在日或星期几的域上
    2:分隔符[",","-","/","*"];eg:在分钟域使用12/15(从12分开始每隔15分钟触发)
    3: 星期(1-7)
    4:日跟星期的域不能是互斥的,不能同时使用
    5:完整的例子:0 15,25,35 9-17 ? * 6 2017-2018 = 2017年和2018年的6月份每天9点到17点分钟刻度为15或25或35时触发




    调度器的设置和功能信息
    SchedulerMetaData sm = s.getMetaData();




    Job参数:
    往具体的Job里传递参数

    JobDataMap jobParam= jobdetail.getJobDataMap();
    jobParam.put("","");
    Job任务里获取:JobExecutionContext/ctx.getJobDetail().getJobDataMap().get()

    JobBuilder.usingJobData(),取时同上

    JobDataMap jobParam = JobExecutionContext/ctx.getMergedJobDataMap()


    监听器管理器:
    例:给指定key的任务增加监听器
    ListenerManager lm= schedule.getListenerManager();
    Matcher<JobKey> matcher = KeyMatcher.keyEquals(job.getKey());
    lm.addJobListener(new MyListener(),matcher);


    二:配置文件

    quartz有一个默认的配置文件,在quarz包里,如果需要更改配置文件信息,需要将该文件复制一份到src下

    如果需要用到数据库存储

    #org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX

    #org.quartz.jobStore.driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate

    #org.quartz.jobStore.tablePrefix: QRTZ_

    #org.quartz.jobStore.useProperties: true


    #org.quartz.jobStore.dataSource: ds 

    #org.quartz.dataSource.ds.driver: com.mysql.jdbc.Driver 

    #org.quartz.dataSource.ds.URL: jdbc:mysql://127.0.0.1:3306/quartz?useUnicode=true&characterEncoding=UTF-8

    #org.quartz.dataSource.ds.user: emil 

    #org.quartz.dataSource.ds.password: 123456

    以上部分为开启JDBCStore,其实没啥用,就记录了一下还未跑完的任务,已经跑完的就不知所踪了,如果需要自己记录任务的详细情况,自己动手写吧。

    #配置一个全局的任务监听器,当然这个也是可以在代码中添加的

    org.quartz.jobListener.NAME.class = MyListener

    更多详细的配置可以参考官方网站:http://www.quartz-scheduler.org/documentation/quartz-2.2.x/configuration/


    入门demo:

    try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            JobDetail jobdetail = JobBuilder.newJob(MyJob.class).withIdentity("任务名字").build();
            Trigger trigger = TriggerBuilder.newTrigger() 
                    .withIdentity("触发器名字")
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(5).withRepeatCount(3))
                    .build();
            // and start it off
            scheduler.scheduleJob(jobdetail, trigger);
            scheduler.start();
        } catch (SchedulerException se) {
            se.printStackTrace();
        }


    Job:

    public class MyJob implements Job{
    
    	@Override
    	public void execute(JobExecutionContext context) throws JobExecutionException {
    		//通过上下文获取  
            JobKey jobKey = context.getJobDetail().getKey();  
            System.out.println("任务id>>>>>>>>>>>>>>>"+jobKey);
            for(int i=0;i<5;i++) {
            	    System.out.println("i am a superman");
            }
    	}
    }




    展开全文
  • quartz

    千次阅读 2012-06-04 17:34:56
    package myschedule.service.quartz; import static myschedule.service.ErrorCode.SCHEDULER_PROBLEM; import static org.quartz.CalendarIntervalScheduleBuilder.calendarIntervalSchedule; import static o

     

    package myschedule.service.quartz;
    
    import static myschedule.service.ErrorCode.SCHEDULER_PROBLEM;
    import static org.quartz.CalendarIntervalScheduleBuilder.calendarIntervalSchedule;
    import static org.quartz.CronScheduleBuilder.cronSchedule;
    import static org.quartz.JobBuilder.newJob;
    import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
    import static org.quartz.TriggerBuilder.newTrigger;
    
    import java.io.ByteArrayInputStream;
    import java.io.InputStream;
    import java.text.ParseException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    import myschedule.service.ErrorCodeException;
    
    import org.quartz.Calendar;
    import org.quartz.CalendarIntervalTrigger;
    import org.quartz.CronTrigger;
    import org.quartz.DateBuilder.IntervalUnit;
    import org.quartz.Job;
    import org.quartz.JobDetail;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobKey;
    import org.quartz.Scheduler;
    import org.quartz.SchedulerException;
    import org.quartz.SchedulerMetaData;
    import org.quartz.SimpleTrigger;
    import org.quartz.Trigger;
    import org.quartz.TriggerKey;
    import org.quartz.impl.matchers.GroupMatcher;
    import org.quartz.spi.MutableTrigger;
    import org.quartz.spi.OperableTrigger;
    
    /**
     * A template to simplify quartz Scheduler class. It provides some more convenient methods to schedule
     * jobs and convert Quartz's "checked" SchedulerException into an "unchecked" ErrorCodeException.
     *
     * @author Zemian Deng
     */
    public class SchedulerTemplate {
    	
    	protected Scheduler scheduler;
    	
    	public SchedulerTemplate(Scheduler scheduler) {
    		this.scheduler = scheduler;
    	}
    
    	public void setScheduler(Scheduler scheduler) {
    		this.scheduler = scheduler;
    	}
    	
    	public Scheduler getScheduler() {
    		return scheduler;
    	}
    
    	public List<String> getCalendarNames() {
    		try {
    			return scheduler.getCalendarNames();
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	public boolean isShutdown() {
    		try {
    			return scheduler.isShutdown();
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	
    	public boolean isInStandbyMode() {
    		try {
    			return scheduler.isInStandbyMode();
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	public boolean isStarted() {
    		try {
    			return scheduler.isStarted();
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	public List<JobExecutionContext> getCurrentlyExecutingJobs() {
    		try {
    			List<JobExecutionContext> result = new ArrayList<JobExecutionContext>();
    			List<?> jobs = scheduler.getCurrentlyExecutingJobs();
    			for (Object job : jobs) {
    				JobExecutionContext jobec = (JobExecutionContext)job;
    				result.add(jobec);
    			}
    			return result;
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	public SchedulerMetaData getSchedulerMetaData() {
    		try {
    			return scheduler.getMetaData();
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	/** Get all the JobDetails in the scheduler. */
    	public List<JobDetail> getJobDetails() {
    		try {
    			List<JobDetail> jobs = new ArrayList<JobDetail>();
    			List<String> groups = scheduler.getJobGroupNames();
    			for (String group : groups) {
    				Set<JobKey> keys = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(group));
    				for (JobKey key : keys) {
    					JobDetail jobDetail = scheduler.getJobDetail(key);
    					jobs.add(jobDetail);
    				}
    			}
    			return jobs;
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	/** Get all the triggers in the scheduler. */
    	public List<? extends Trigger> getTriggers(JobDetail jobDetail) {
    		try {
    			List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobDetail.getKey());
    			return triggers;
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	public JobDetail getJobDetail(String jobName, String group) {	
    		try {
    			JobKey key = JobKey.jobKey(jobName, group);
    			return scheduler.getJobDetail(key);
    		} catch (Exception e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	public Trigger getTrigger(String triggerName, String group) {	
    		try {
    			TriggerKey key = TriggerKey.triggerKey(triggerName, group);
    			return scheduler.getTrigger(key);
    		} catch (Exception e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	public Calendar getCalendar(String calName) {	
    		try {
    			return scheduler.getCalendar(calName);
    		} catch (Exception e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	/**
    	 * Get a list of next fire time dates up to maxCount time. If next fire time needed
    	 * before maxCount, then there should be a null object in the last element of the list.
    	 */
    	public List<Date> getNextFireTimes(Trigger trigger, Date startTime, int maxCount) {
    		// We will clone the original trigger so we may call its triggered() to get a proper fireTime.
    		OperableTrigger clonedTrigger = (OperableTrigger)((OperableTrigger)trigger).clone();
    		Calendar cal = null;
    		
            if (clonedTrigger.getNextFireTime() == null) {
            	clonedTrigger.computeFirstFireTime(cal);
            }
            
    		List<Date> list = new ArrayList<Date>();
    		Date nextDate = startTime;
    		int count = 0;
    		while(count++ < maxCount) {
    			nextDate = clonedTrigger.getFireTimeAfter(nextDate);
    			if (nextDate == null)
    				break;
    			list.add(nextDate);
    			clonedTrigger.triggered(cal);
    		}
    		return list;
    	}
    	
    	/**
    	 * Get a list of next fire time dates up to maxCount time. If next fire time needed
    	 * before maxCount, then there should be a null object in the last element of the list.
    	 */
    	public List<Date> getNextFireTimesWithCalendar(Trigger trigger, Date startTime, int maxCount) {
    		List<Date> dates = getNextFireTimes(trigger, startTime, maxCount);
    		String calName = trigger.getCalendarName();
    		if (calName == null) {
    			return dates;
    		}
    		
    		// Else check if dates has excluded by calendar or not.
    		Calendar cal = getCalendar(calName);
    		List<Date> result = new ArrayList<Date>();
    		for (Date dt : dates) {
    			if (cal.isTimeIncluded(dt.getTime())) {
    				result.add(dt);
    			}
    		}
    		return result;
    	}
    	
    	/** Update existing job with newJobDetail and return the old one. */
    	public JobDetail updateJobDetail(JobDetail newJobDetail) {
    		try {
    			JobDetail oldJob = scheduler.getJobDetail(newJobDetail.getKey());
    			scheduler.addJob(newJobDetail, true);
    			return oldJob;
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	/** Update existing trigger with newTrigger and return the old one. */
    	public Trigger updateTrigger(Trigger newTrigger) {
    		try {
    			Trigger oldTrigger = scheduler.getTrigger(newTrigger.getKey());
    			scheduler.rescheduleJob(oldTrigger.getKey(), newTrigger);
    			return oldTrigger;
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	/** Add a JobDetail with a trigger schedule when to fire. */
    	public Date scheduleJob(JobDetail jobDetail, Trigger trigger) {
    		try {
    			Date nextFireTime = scheduler.scheduleJob(jobDetail, trigger);
    			return nextFireTime;
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	/** Schedule new trigger to an existing JobDetail. You need to set "trigger.setJobName()". */
    	public void scheduleJob(Trigger trigger) {
    		try {
    			scheduler.scheduleJob(trigger);
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	/** Remove a trigger and its JobDetail if it's not set durable. */
    	public Trigger uncheduleJob(String triggerName, String triggerGroup) {
    		try {
    			Trigger trigger = scheduler.getTrigger(TriggerKey.triggerKey(triggerName, triggerGroup));
    			boolean success = scheduler.unscheduleJob(trigger.getKey());
    			if (!success)
    				throw new SchedulerException("Failed to unschedule job. Trigger name=" + 
    						triggerName + ", group=" + triggerGroup);
    			return trigger;
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	public void addJob(JobDetail job, boolean replace) {
    		try {
    			scheduler.addJob(job, replace);
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	/** Remove a JobDetail and all the triggers associated with it. */
    	public List<? extends Trigger> deleteJob(String jobName, String group) {
    		try {
    			JobKey key = JobKey.jobKey(jobName, group);
    			List<? extends Trigger> triggers = scheduler.getTriggersOfJob(key);
    			boolean success = scheduler.deleteJob(key);
    			if (!success)
    				throw new SchedulerException("Unable to delete job " + key);
    			return triggers;
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	/**
    	 * Load job scheduling data xml using XMLSchedulingDataProcessor.
    	 * @param xml - xml content of job_scheduling_data xml.
    	 * @return XMLSchedulingDataProcessor instance will contain all the jobs parse in xml.
    	 */
    	public XmlJobLoader scheduleXmlSchedulingData(String xml) {
    		try {
    			// XmlJobLoader is not only just a loader, but also use to store what's loaded!
    			XmlJobLoader xmlJobLoader = XmlJobLoader.newInstance(); 
    			String systemId = XmlJobLoader.XML_SYSTEM_ID;
    			InputStream istream = new ByteArrayInputStream(xml.getBytes());
    			xmlJobLoader.processStreamAndScheduleJobs(istream, systemId, scheduler);
    			return xmlJobLoader;
    		} catch (Exception e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	/** Run a job immediately with a non-volatile trigger (remove as soon as it's finished.) */
    	public void runJobNow(String name, String group) {
    		try {
    			JobKey key = JobKey.jobKey(name, group);
    			scheduler.triggerJob(key);
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	public static JobDetail createJobDetail(String name, Class<? extends Job> jobClass) {
    		return createJobDetail(name, null, true, jobClass, null);
    	}
    	
    	public static JobDetail createJobDetail(String name, String group, boolean durable, Class<? extends Job> jobClass, Map<String, Object> data) {
    		JobDetail jobDetail = newJob(jobClass).withIdentity(name, group).storeDurably(durable).build();
    		if (data != null)
    			jobDetail.getJobDataMap().putAll(data);
    		return jobDetail;
    	}	
    
    	public static MutableTrigger createCalendarIntervalTrigger(
    			String name, int interval, IntervalUnit intervalUnit) {
    		return createCalendarIntervalTrigger(name, null, interval, intervalUnit, null, null);
    	}
    	
    	public static MutableTrigger createCalendarIntervalTrigger(
    			String name, String group,
    			int interval, IntervalUnit intervalUnit,
    			Date startTime, Date endTime) {
    		if (group == null)
    			group = Scheduler.DEFAULT_GROUP;
    		
    		if (startTime == null)
    			startTime = new Date();
    		
    		CalendarIntervalTrigger trigger = newTrigger()
    				.withIdentity(name, group)
    				.startAt(startTime).endAt(endTime)
    				.withSchedule(calendarIntervalSchedule().withInterval(interval, intervalUnit))
    				.build();
    		return (MutableTrigger)trigger;
    	}
    	
    	public static MutableTrigger createCronTrigger(String name, String cron) {
    		return createCronTrigger(name, null, cron, null, null);
    	}
    	
    	public static MutableTrigger createCronTrigger(String name, String group, String cron, Date startTime, Date endTime) {
    		if (group == null)
    			group = Scheduler.DEFAULT_GROUP;
    		
    		if (startTime == null)
    			startTime = new Date();
    		
    		try {
    			CronTrigger trigger = newTrigger()
    					.withIdentity(name, group)
    					.startAt(startTime).endAt(endTime)
    					.withSchedule(cronSchedule(cron))
    					.build();
    			return (MutableTrigger)trigger;
    		} catch (ParseException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	public static MutableTrigger createSimpleTrigger(String name, String group, int repeatTotalCount, long repeatInterval, Date startTime, Date endTime) {
    		if (group == null)
    			group = Scheduler.DEFAULT_GROUP;
    		
    		if (startTime == null)
    			startTime = new Date();
    		
    		// Quartz's SimpleTrigger's repeatCount is one less than repeatTotalCount, so we need to adjust.
    		int repeatCount = repeatTotalCount - 1;
    		if (repeatTotalCount < 0)
    			repeatCount = SimpleTrigger.REPEAT_INDEFINITELY;
    		
    		SimpleTrigger trigger = newTrigger()
    			.withIdentity(name, group)
    			.startAt(startTime).endAt(endTime)
    			.withSchedule(
    					simpleSchedule()
    					.withRepeatCount(repeatCount)
    					.withIntervalInMilliseconds(repeatInterval))
    			.build();
    		return (MutableTrigger)trigger;
    	}
    	
    	public Date scheduleCronJob(
    			String name, String group, String cron, 
    			Date startTime, Date endTime,
    			Class<? extends Job> jobClass, Map<String, Object> data) {
    		JobDetail job = createJobDetail(name, group, false, jobClass, data);
    		Trigger trigger = createCronTrigger(name, group, cron, startTime, endTime);
    		return scheduleJob(job, trigger);
    	}
    
    	public Date scheduleRepeatForeverJob(String name, long repeatInterval, Class<? extends Job> jobClass) {
    		return scheduleRepeatableJob(name, null, null, null, -1, repeatInterval, jobClass, null);
    	}
    	
    	public Date scheduleRepeatableJob(String name, int repeatCount, long repeatInterval, Class<? extends Job> jobClass) {
    		return scheduleRepeatableJob(name, null, null, null, repeatCount, repeatInterval, jobClass, null);
    	}
    	
    	public Date scheduleRepeatableJob(
    			String name, String group, Date startTime, Date endTime,
    			int repeatTotalCount, long repeatInterval,
    			Class<? extends Job> jobClass, Map<String, Object> data) {
    		JobDetail job = createJobDetail(name, group, false, jobClass, data);
    		Trigger trigger = createSimpleTrigger(name, group, repeatTotalCount, repeatInterval, startTime, endTime);
    		return scheduleJob(job, trigger);
    	}
    	
    	public Date scheduleOnetimeJob(String name, Class<? extends Job> jobClass) {
    		return scheduleRepeatableJob(name, 1, 0, jobClass);
    	}
    	
    	public Date scheduleOnetimeJob(String name, String group, Date startTime, Date endTime, 
    			Class<? extends Job> jobClass, Map<String, Object> data) {
    		return scheduleRepeatableJob(name, group, startTime, endTime, 1, 0, jobClass, data);
    	}
    
    	public String getSchedulerName() {
    		try {
    			return scheduler.getSchedulerName();
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    	
    	public String getSchedulerInstanceId() {
    		try {
    			return scheduler.getSchedulerInstanceId();
    		} catch (SchedulerException e) {
    			throw new ErrorCodeException(SCHEDULER_PROBLEM, e);
    		}
    	}
    
    	public String getSchedulerNameAndId() {
    		return getSchedulerName() + "_$_" + getSchedulerInstanceId();
    	}
    	
    	@Override
    	public String toString() {
    		return "QuartzScheduler[" + getSchedulerNameAndId() + "]";
    	}
    }
    
    展开全文
  • Quartz 定时任务调度框架

    万次阅读 2020-10-06 19:40:36
    定时任务调度框架 Quartz 入门案例: 依赖: <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> ...

    Quartz 定时任务调度框架

    入门案例:

    • 依赖:
    <dependency>
    	<groupId>org.quartz-scheduler</groupId>
    	<artifactId>quartz</artifactId>
    	<version>2.3.2</version>
    </dependency>
    <dependency>
    	<groupId>org.quartz-scheduler</groupId>
    	<artifactId>quartz-jobs</artifactId>
    	<version>2.3.2</version>
    </dependency>
    
    • Job类:
    package com.blu.job;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    
    public class HelloJob implements Job{
    
    	@Override
    	public void execute(JobExecutionContext context) throws JobExecutionException {
    		Date date = new Date();
    		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		String dateString = dateFormat.format(date);
    		System.out.println("当前时间:"+dateString);
    	}
    
    }
    
    • 测试类:
    package com.blu.test;
    
    import org.quartz.JobBuilder;
    import org.quartz.JobDetail;
    import org.quartz.Scheduler;
    import org.quartz.SimpleScheduleBuilder;
    import org.quartz.Trigger;
    import org.quartz.TriggerBuilder;
    import org.quartz.impl.StdSchedulerFactory;
    import com.blu.job.HelloJob;
    
    public class HelloScheduleTest {
    
    	public static void main(String[] args) throws Exception {
    		//调度器(Scheduler),从工厂中获取
    		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    		//任务示例(JobDetail)
    		JobDetail jobDetail = JobBuilder.newJob(HelloJob.class).withIdentity("job1", "JobGroup1").build();
    		//触发器(Trigger)
    		Trigger trigger = TriggerBuilder.newTrigger()
    					.withIdentity("trigger1", "TriggerGroup1")
    					//立即启动触发器
    					.startNow()
    					//每5s重复执行一次
    					.withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatSecondlyForever(5))
    					.build();
    		//让调度器关联任务和触发器
    		scheduler.scheduleJob(jobDetail,trigger);
    		scheduler.start();
    	}
    
    }
    
    • 运行效果:每5s打印一次时间
    当前时间:2020-10-06 19:34:09
    当前时间:2020-10-06 19:34:14
    当前时间:2020-10-06 19:34:19
    当前时间:2020-10-06 19:34:24
    当前时间:2020-10-06 19:34:29
    当前时间:2020-10-06 19:34:34
    当前时间:2020-10-06 19:34:39
    当前时间:2020-10-06 19:34:44
    当前时间:2020-10-06 19:34:49
    当前时间:2020-10-06 19:34:54
    当前时间:2020-10-06 19:34:59
    当前时间:2020-10-06 19:35:04
    

    扩展

    • Job类:
    package com.blu.job;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.quartz.Job;
    import org.quartz.JobDataMap;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    import org.quartz.JobKey;
    import org.quartz.Trigger;
    
    public class HelloJob implements Job{
    	
    	private String message;
    	
    	public void setMessage(String message) {
    		this.message = message;
    	}
    
    	@Override
    	public void execute(JobExecutionContext context) throws JobExecutionException {
    		Date date = new Date();
    		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		String dateString = dateFormat.format(date);
    		//获取JobDetail的内容
    		JobKey jobKey = context.getJobDetail().getKey();
    		System.out.println(jobKey.getName());
    		System.out.println(jobKey.getGroup());
    		System.out.println(context.getJobDetail().getJobClass().getName());
    		//从JobDetail对象中获取JobDataMap的数据
    		JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
    		String jobDataMessage = jobDataMap.getString("message");
    		System.out.println(jobDataMessage);
    		//从Trigger对象中获取JobDataMap的数据
    		JobDataMap  triggerDataMap = context.getTrigger().getJobDataMap();
    		String triggerDataMessage = triggerDataMap.getString("message");
    		System.out.println(triggerDataMessage);
    		//获取Trigger中的内容
    		Trigger trigger = context.getTrigger();
    		System.out.println(trigger.getKey().getName());
    		System.out.println(trigger.getKey().getGroup());
    		System.out.println(trigger.getKey().getClass());
    		//初始化job类示例对象时会自动调用setter方法为属性赋值
    		//当trigger与JobDetail设置了重名属性时,setter方法获取的值就是trigger设置的属性值                                                                       
    		System.out.println("通过setter直接获取数据:"+message);
    		//获取其他内容
    		System.out.println("当前任务执行时间"+dateFormat.format(context.getFireTime()));
    		System.out.println("下次任务的执行时间"+dateFormat.format(context.getNextFireTime()));
    		System.out.println("当前时间:"+dateString);
    	}
    
    }
    
    • 测试类:
    package com.blu.test;
    
    import org.quartz.JobBuilder;
    import org.quartz.JobDetail;
    import org.quartz.Scheduler;
    import org.quartz.SimpleScheduleBuilder;
    import org.quartz.Trigger;
    import org.quartz.TriggerBuilder;
    import org.quartz.impl.StdSchedulerFactory;
    
    import com.blu.job.HelloJob;
    
    public class HelloScheduleTest {
    
    	public static void main(String[] args) throws Exception {
    		//调度器(Scheduler),从工厂中获取
    		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    		//任务示例(JobDetail)
    		JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
    					.withIdentity("job1", "JobGroup1")
    					.usingJobData("message","jobDetail传递的值")
    					.build();
    //		System.out.println(jobDetail.getKey().getName());
    //		System.out.println(jobDetail.getKey().getGroup());
    //		System.out.println(jobDetail.getKey().getClass());
    		//触发器(Trigger)
    		Trigger trigger = TriggerBuilder.newTrigger()
    					.withIdentity("trigger1", "TriggerGroup1")
    					//立即启动触发器
    					.startNow()
    					//每5s重复执行一次
    					.withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatSecondlyForever(5))
    					.usingJobData("message","trigger传递的值")
    					.build();
    		//让调度器关联任务和触发器
    		scheduler.scheduleJob(jobDetail,trigger);
    		scheduler.start();
    	}
    
    }
    
    • 运行结果
    job1
    JobGroup1
    com.blu.job.HelloJob
    jobDetail传递的值
    trigger传递的值
    trigger1
    TriggerGroup1
    class org.quartz.TriggerKey
    通过setter直接获取数据:trigger传递的值
    当前任务执行时间2020-10-08 13:52:33
    下次任务的执行时间2020-10-08 13:52:38
    当前时间:2020-10-08 13:52:33
    
    job1
    JobGroup1
    com.blu.job.HelloJob
    jobDetail传递的值
    trigger传递的值
    trigger1
    TriggerGroup1
    class org.quartz.TriggerKey
    通过setter直接获取数据:trigger传递的值
    当前任务执行时间2020-10-08 13:52:38
    下次任务的执行时间2020-10-08 13:52:43
    当前时间:2020-10-08 13:52:38
    
    job1
    JobGroup1
    com.blu.job.HelloJob
    jobDetail传递的值
    trigger传递的值
    trigger1
    TriggerGroup1
    class org.quartz.TriggerKey
    通过setter直接获取数据:trigger传递的值
    当前任务执行时间2020-10-08 13:52:43
    下次任务的执行时间2020-10-08 13:52:48
    当前时间:2020-10-08 13:52:43
    

    @PersistJobDataAfterExecution 有状态的Job和无状态的Job:

    每次执行任务时都会创建一个新的Job实例

    默认的无状态Job每次调用时都会创建一个新的JobDataMap

    而有状态的Job在多次Job调用期间可以在JobDataMap中存储一些状态信息

    • Job类:
    package com.blu.job;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    
    @PersistJobDataAfterExecution
    public class HiJob implements Job{
    	
    	private Integer count;
    
    	public void setCount(Integer count) {
    		this.count = count;
    	}
    
    	@Override
    	public void execute(JobExecutionContext context) throws JobExecutionException {
    		
    		Date date = new Date();
    		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		System.out.println("当前时间:"+ dateFormat.format(date));
    		
    		//累加count,输出count,存入JobDataMap
    		count++;
    		System.out.println(count);
    		context.getJobDetail().getJobDataMap().put("count", count);
    		
    	}
    	
    }
    
    • 测试类:
    package com.blu.test;
    
    import org.quartz.JobBuilder;
    import org.quartz.JobDetail;
    import org.quartz.Scheduler;
    import org.quartz.SimpleScheduleBuilder;
    import org.quartz.Trigger;
    import org.quartz.TriggerBuilder;
    import org.quartz.impl.StdSchedulerFactory;
    
    import com.blu.job.HiJob;
    
    public class HiTest {
    
    	public static void main(String[] args) throws Exception {
    		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    		JobDetail jobDetail = JobBuilder.newJob(HiJob.class)
    								.usingJobData("count",0)
    								.build();
    		
    		Trigger trigger = TriggerBuilder.newTrigger()
    								.startNow()
    								.withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatSecondlyForever(5))
    								.build();
    		
    		scheduler.scheduleJob(jobDetail,trigger);
    		scheduler.start();
    				
    	}
    	
    }
    

    不加 @PersistJobDataAfterExecution 注解时是无状态Job,运行效果:

    当前时间:2020-10-09 11:03:53
    1
    当前时间:2020-10-09 11:03:58
    1
    当前时间:2020-10-09 11:04:03
    1
    当前时间:2020-10-09 11:04:08
    1
    当前时间:2020-10-09 11:04:13
    1
    当前时间:2020-10-09 11:04:18
    1
    

    加上 @PersistJobDataAfterExecution 注解后是有状态Job,运行效果:

    当前时间:2020-10-09 11:06:25
    1
    当前时间:2020-10-09 11:06:30
    2
    当前时间:2020-10-09 11:06:35
    3
    当前时间:2020-10-09 11:06:40
    4
    当前时间:2020-10-09 11:06:45
    5
    当前时间:2020-10-09 11:06:50
    6
    

    其他注解:

    @DisallowConcurrentExecution

    默认的情况下,无论上一次任务是否结束或者完成,只要规定的时间到了,那么下一次就开始。

    使用 @DisallowConcurrentExecution 注解可以保证上一次任务成功结束后,下一次任务才能开始

    展开全文
  • Spring+Quartz实现定时任务的配置方法

    万次阅读 多人点赞 2019-07-31 19:16:18
    <bean id="teachingProcessTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <!-- 每天凌晨0点执行一次 --> <value>0 0 0 * * ? <!-- JobDetail配置 --> ...
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    	xsi:schemaLocation="
    		http://www.springframework.org/schema/beans 
    		http://www.springframework.org/schema/beans/spring-beans.xsd
    		http://www.springframework.org/schema/context
    		http://www.springframework.org/schema/context/spring-context.xsd
    		http://www.springframework.org/schema/tx 
    		http://www.springframework.org/schema/tx/spring-tx.xsd
    		http://www.springframework.org/schema/aop 
    		http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--  Scheduler配置 -->
    	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    		<property name="triggers">
    			<list>
    				<ref bean="teachingProcessTrigger" />
    			</list>
    		</property>
    		<property name="quartzProperties">
    			<props>
    				<prop key="org.quartz.threadPool.threadCount">3</prop>
    			</props>
    		</property>
    	</bean>
    <!--  Trigger配置 -->
    	<bean id="teachingProcessTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
    		<property name="jobDetail">
    			<ref bean="teachingProcess" />
    		</property>
    		<property name="cronExpression">
    			<!--  每天凌晨0点执行一次 -->
    			<value>0 0 0 * * ?</value>
    		</property>
    	</bean>
    <!--  JobDetail配置 -->
    	<bean id="teachingProcess"
    		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    		<property name="targetObject">
        <!-- hrQuartzServiceImpl是一个业务类,在其他地方声明了bean,这里直接引用就可以 -->
    			<ref bean="hrQuartzServiceImpl" />
    		</property>
    		<property name="targetMethod">
        <!-- hrQuartzServiceImpl类里作为执行入口的方法名 -->
    			<value>doTeachingProcess</value>
    		</property>
    	</bean>
    </beans>
    

    任务有并行和串行之分,并行是指:一个定时任务,当执行时间到了的时候,立刻执行此任务,不管当前这个任务是否在执行中;串行是指:一个定时任务,当执行时间到了的时候,需要等待当前任务执行完毕,再去执行下一个任务。
    quartz框架中可以设置是否允许任务并行:
    如果是通过MethodInvokingJobDetailFactoryBean在运行中动态生成的Job,配置的xml文件有个concurrent属性,这个属性的功能是配置此job是否可以并行运行,如果为false则表示不可以并行运行,否则可以并行。如果一个job的业务处理发费的时间超过了job的启动的间隔时间(repeatInterval),这个属性非常有用。如果为false,那么,在这种情况下,当前job还在运行,那么下一个job只能延时运行。如果为true,那么job就会并行运行,配置示例如下:

    <bean id="jobCompareB2cAndLocal" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    	<property name="targetObject " ref="delegateJob " />
    	<property name="targetMethod " value="方法名" />
    	<property name="concurrent " value="false " />
    </bean >
    

    如果不配置,默认是true的,就是允许并行。

    展开全文
  • 定时任务框架Quartz-(一)Quartz入门与Demo搭建

    万次阅读 多人点赞 2018-07-10 13:57:07
    一、什么是Quartz 什么是Quartz? Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,完全由Java开发,可以用来执行定时任务,类似于java.util.Timer。但是相较于Timer, Quartz增加了很多功能:...
  • Quartz 入门详解

    万次阅读 2017-05-23 14:39:18
    基本上任何公司都会用到调度这个功能, 比如我们公司需要定期执行调度生成报表, 或者比如博客什么的定时更新之类的,都可以靠Quartz来完成。正如官网所说,小到独立应用大到大型电子商务网站, Quartz都能胜任。...
  • 精进 QuartzQuartz大致介绍(一)

    万次阅读 多人点赞 2017-02-04 15:13:26
    Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,是完全由java开发的一个开源的任务日程管理系统,“任务进度管理器”就是一个在预先确定(被纳入日程)的时间到达时,负责执行(或者通知)其他...
  • 精进Quartz—Spring和Quartz集成详解(三)

    万次阅读 多人点赞 2017-02-06 11:49:46
    Spring是一个很优秀的框架,它无缝的集成了Quartz,简单方便的让企业级应用更好的使用Quartz进行任务的调度。下面就对Spring集成Quartz进行简单的介绍和示例讲解!和上一节 Quartz学习——2、简单入门示例Demo 的...
  • Quartz简介

    千次阅读 2020-11-22 12:38:15
    文章目录Quartz 是什么What is the Quartz Job Scheduling Library?使用场景特点Quartz 使用的设计模式核心元素SchedulerTriggerCalendarJobDetailJobJobExecutionContext核心元素之间的关系Quartz 类图主要线程数据...
  • 精进QuartzQuartz简单入门Demo(二)

    万次阅读 多人点赞 2017-02-04 15:55:38
    要学习Quartz框架,首先大概了解了Quartz的基本知识后,在通过简单的例子入门,一步一个脚印的走下去。 下面介绍Quartz入门的示例,由于Quartz的存储方式分为RAM和JDBC,分别对这两种进行简单的说明。并附上代码! ...
  • Spring Quartz spring 分别对Quartz的三个方面,Job & JobDetail,Trigger和Scheduler进行了封装,Spring Quartz 和 Spring Scheduling是任务调度的两种方案,两者在使用上完全没有关系,Spring Scheduling使用的...
  • quartz quartz-1.8.6 dbTables 建表sql

    热门讨论 2013-08-08 18:31:19
    quartz quartz-1.8.6 dbTables quartz动态任务调度需要的数据库脚本。
  • Quartz概述

    千次阅读 2016-09-04 11:42:17
    Quartz是开源任务调度框架中的翘楚,它提供了强大的 任务调度机制。Quartz允许开发人员灵活的定义触发器的调度时间表,并可对触发器和任务进行关联映射。此外,Quartz提供了调度运行环境的持久化机制,可以保存并...
  • quartz定时器

    千次阅读 2019-06-27 09:51:18
    一、关于 Quartz Quartz 是一个完全由 Java 编写的开源作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。 Quartz 可以与 J2EE 与 J2SE 应用程序相结合也可以单独使用。 ...
  • Quartz Cluster

    2019-03-31 15:56:05
    基于数据库JobStore的Quartz Cluster实现 ClusterManager 如果开启cluster的话,ClusterManager线程会运行,参见JobStroeSupport#scheduleStarted(); ClusterCheck这个check是check啥,参看JobStoreSupport#...
  • Scheduler class: ‘org.quartz.core.QuartzScheduler’ - running locally. NOT STARTED. Currently in standby mode. Number of jobs executed: 0 Using thread pool ‘org.quartz.simpl.SimpleThreadPool’ - ...
  • 林炳文Evankaka原创作品。... 一、 Quartz存储与持久化  Quartz提供两种基本作业存储...在默认情况下Quartz将任务调度的运行信息保存在内存中,这种方法提供了最佳的性能,因为内存中数据访问最快。不足之处是缺乏...
  • Quartz-异常处理

    万次阅读 2017-11-15 13:18:17
    示例源码概述我们根据官网示例说明Quartz在job执行异常情况时的处理。参考官方原文: http://www.quartz-scheduler.org/documentation/quartz-2.2.x/examples/Example6.html本文涉及3个类: BadJob1.java、 ...
  • Quartz报错

    万次阅读 热门讨论 2017-11-28 16:21:57
    Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.  NOT STARTED.  Currently in standby mode.  Number of jobs executed: 0  Using thread pool 'org.quartz.simpl.SimpleThreadPoo

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 41,312
精华内容 16,524
关键字:

quartz