quartz定时任务

quartz定时任务,之前在网上找了一堆,几乎全是和spring集成的,配置各种文件真麻烦,现在多简洁,如下:

package com.quartz;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class HelloJob implements Job {
	public void execute(JobExecutionContext context)
			throws JobExecutionException {

		// 5
		System.out.println(new Date() + " : Hello Quartz!");

	}

}
package com.quartz;

import org.quartz.CronScheduleBuilder;
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;

/**
 * 
 * @author 
 *
 */
public class QuartzTest {

	public static void main(String[] args) throws SchedulerException {

		//1
		JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity(
				"JobName", "group1").build();

         //5秒执行一次
		/*		Trigger trigger = TriggerBuilder.newTrigger().withIdentity(
				"TriggerName", "group1").withSchedule(
				SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5)
						.repeatForever()).build();
		*/
		
		//2,5秒执行一次,上面的生成trigger的两种方法都行
		Trigger trigger = TriggerBuilder
				.newTrigger()
				.withIdentity("TriggerName", "group1")
				.withSchedule(
					CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
				.build();
		
		//3 schedule it
		Scheduler scheduler = new StdSchedulerFactory().getScheduler();
		scheduler.start();
		//4
		scheduler.scheduleJob(job, trigger);
	}
}
org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 3 
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
输出:

log4j:WARN No appenders could be found for logger (org.quartz.impl.StdSchedulerFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Sat May 20 17:17:50 CST 2017 : Hello Quartz!
Sat May 20 17:17:55 CST 2017 : Hello Quartz!
Sat May 20 17:18:00 CST 2017 : Hello Quartz!
执行顺序是1 2 3 4 5 5 5 5 5 5 .......

参考:

http://www.yiibai.com/quartz/quartz-helloworld.html 









相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页