Quartz regular tasks implemented by spring

Quartz introduction:

Quartz is OpenSymphony open source organization and an open source project in Job scheduling field, it can be combined with J2EE and J2SE applications can also be used alone. Quartz can be used to create simple or run ten, one hundred, or even tens of thousands of Jobs such a complex program. And we write Java programs often write some regular tasks to perform, such as a month to perform a few numbers thing, do something every day in the morning, or what method is performed once a day, then I put a simple, entry Quartz examples put to, it can be run directly, are additions and deletions to change search the Quartz series, can for beginners, there is a general understanding.

QuartzManager (CRUD method):

package com.joyce.quartz;
 
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
 
public class QuartzManager {
	private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
	private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME";
	private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";
 
	/**
	 * 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
	 * @param jobName 任务名
	 * @param cls 任务
	 * @param time 时间设置
	 */
	@SuppressWarnings("rawtypes")
	public static void addJob(String jobName, Class cls, String time) {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			// 任务名,任务组,任务执行类
			JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, cls);
			//可以传递参数
			jobDetail.getJobDataMap().put("param", "railsboy");
			// 触发器
			CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);
			// 触发器名,触发器组
			trigger.setCronExpression(time);
			// 触发器时间设定
			sched.scheduleJob(jobDetail, trigger);
			// 启动
			if (!sched.isShutdown()) {
				sched.start();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
	 * @param jobName
	 * @param time
	 */
	@SuppressWarnings("rawtypes")
	public static void modifyJobTime(String jobName, String time) {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName,TRIGGER_GROUP_NAME);
			if (trigger == null) {
				return;
			}
			String oldTime = trigger.getCronExpression();
			if (!oldTime.equalsIgnoreCase(time)) {
				JobDetail jobDetail = sched.getJobDetail(jobName,JOB_GROUP_NAME);
				Class objJobClass = jobDetail.getJobClass();
				removeJob(jobName);
				addJob(jobName, objJobClass, time);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
 
 
	/**
	 * 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
	 * @param jobName
	 */
	public static void removeJob(String jobName) {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME);// 停止触发器
			sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME);// 移除触发器
			sched.deleteJob(jobName, JOB_GROUP_NAME);// 删除任务
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
 
	/**
	 * 启动所有定时任务
	 */
	public static void startJobs() {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			sched.start();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
 
	/**
	 * 关闭所有定时任务
	 */
	public static void shutdownJobs() {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			if (!sched.isShutdown()) {
				sched.shutdown();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

QuartzJob (task execution classes):

package com.joyce.quartz;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
 
/**
 * 任务执行类
 */
public class QuartzJob implements Job {
 
	@Override
	public void execute(JobExecutionContext content) throws JobExecutionException {
		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "★★★★★★★★★★★");  
		String jobName = content.getJobDetail().getName();
		JobDataMap dataMap = content.getJobDetail().getJobDataMap();
		String param = dataMap.getString("param");
		System.out.println("传递的参数是="+param +"任务名字是="+jobName);
	}
}

QuartzTest (scheduled task test class):

package com.joyce.quartz.main;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
import com.joyce.quartz.QuartzJob;
import com.joyce.quartz.QuartzManager;
 
public class QuartzTest {
	public static void main(String[] args) {
		try {
			String job_name = "动态任务调度";
			System.out.println("【任务启动】开始(每10秒输出一次)...");  
			QuartzManager.addJob(job_name, QuartzJob.class, "0/10 * * * * ?");
			Thread.sleep(5000);
			System.out.println("【修改时间】开始(每2秒输出一次)...");  
			QuartzManager.modifyJobTime(job_name, "10/2 * * * * ?");  
			Thread.sleep(6000);  
			System.out.println("【移除定时】开始...");  
			QuartzManager.removeJob(job_name);  
			System.out.println("【移除定时】成功");  
			System.out.println("【再次添加定时任务】开始(每10秒输出一次)...");  
			QuartzManager.addJob(job_name, QuartzJob.class, "*/10 * * * * ?");  
			Thread.sleep(60000);  
			System.out.println("【移除定时】开始...");  
			QuartzManager.removeJob(job_name);  
			System.out.println("【移除定时】成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static String formatDateByPattern(Date date,String dateFormat){  
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);  
        String formatTimeStr = null;  
        if (date != null) {  
            formatTimeStr = sdf.format(date);  
        }  
        return formatTimeStr;  
    }  
	public static String getCron(java.util.Date  date){  
	    String dateFormat="ss mm HH dd MM ? yyyy";  
	    return formatDateByPattern(date, dateFormat);  
	 }  
}


 

Using quartz timing of the implementation of tasks required jar package Download: http: //download.csdn.NET/detail/i__am__sai/9719500

Common time configuration:

Format: [seconds] [minutes] [h] [day] [month] [weeks] [years]
? 0012 * * 12:00 every day trigger
? 01510 * * every day 10:15 triggering
01510 * * ? day 10:15 triggering
01510 * *? * daily 10:15 triggering
01510 * *? 2005 2005 daily 10:15 triggering
0 * 14 * *? every afternoon 2:00 to 2:59 points per minute trigger
0 0/5 14 * *? every afternoon 2:00 to 2:59 (the whole point of beginning, every 5 minutes trigger)
0 0/5 * 14, 18 *? 18 o'clock every afternoon to 18 11:59 (the whole point of beginning, every 5 minutes trigger)
00-514 * *? every afternoon 2:00 to 2:05 trigger points each
0 10,44 14? 3 WED 3 Wednesday afternoon of the month 2:10 and 2:44 trigger
0 15 10? * MON-FRI every day from Monday to Friday morning 10:15 triggering
0,151,015 *? 15 each month 10:15 triggering
01510 L *? last day of each month 10:15 triggering
0 15 10? * 6L last week of each month Friday 10:15 triggering
0 15 10? * 6L 2002-2005 from 2002 to 2005, the last week of each month Friday's 10:15 triggering
01510? * 6 # 3 of the third week of each month starting Friday trigger
0012 1/5 *? per month A noon start trigger once every 5 days
011,111,111? Every November 11th 11:11 Trigger (Singles)

Published 21 original articles · won praise 1 · views 7069

Guess you like

Origin blog.csdn.net/AIfurture/article/details/103975813