定时任务Quartz

定时任务Quartz

1.简单java项目中使用Quartz
项目结构

在这里插入图片描述
只需要引入4个jar包即可
在这里插入图片描述
QuartzUtils.java (工具类)

package com.lbl.quartz.utils;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.JobKey.jobKey;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.TriggerKey.triggerKey;

import java.util.Date;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
/**
 * 类说明:定时任务管理工具类
 * @author libl
 *
 */
public class QuartzUtils {
	private static String JOB_NAME = "SERVERM_NAME";
	private static String JOB_GROUP_NAME = "SERVERM_JOBGROUP_NAME";
	private static String TRIGGER_NAME = "SERVERM_NAME";
	private static String TRIGGER_GROUP_NAME = "SERVERM_TRIGGERGROUP_NAME";

	/**
	 * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
	 * @param sched:调度器
	 * @param jobClass:任务
	 * @param time:时间设置,CronExpression表达式
	 */
	public static void addJob(Scheduler sched, @SuppressWarnings("rawtypes") Class jobClass, String time) {
		addJob(sched, jobClass, time, JOB_NAME, JOB_GROUP_NAME, TRIGGER_NAME, TRIGGER_GROUP_NAME);
	}

	/**
	 * @Description: 添加一个定时任务
	 * @param sched:调度器
	 * @param jobClass:任务
	 * @param time:时间设置,CronExpression表达式
	 * @param jobName:任务名
	 * @param jobGroupName:任务组名
	 * @param triggerName:触发器名
	 * @param triggerGroupName:触发器组名
	 */
	public static void addJob(Scheduler sched, @SuppressWarnings("rawtypes") Class jobClass, String time,
			String jobName, String jobGroupName, String triggerName, String triggerGroupName) {

		JobDetail job = newJob(jobClass).withIdentity(jobName, jobGroupName).build();
		CronTrigger trigger = newTrigger().withIdentity(triggerName, triggerGroupName).withSchedule(cronSchedule(time))
				.build();
		try {
			// 返回为 null 添加失败
			Date ft = sched.scheduleJob(job, trigger);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description: 定义一个任务之后进行触发设定(使用默认的任务组名,触发器名,触发器组名)
	 * @param sched:调度器
	 * @param time
	 */
	@SuppressWarnings("rawtypes")
	public static void addJObLaterUse(Scheduler sched, @SuppressWarnings("rawtypes") Class jobClass, String time) {

		addJObLaterUse(sched, jobClass, time, JOB_NAME, JOB_GROUP_NAME);
	}

	/**
	 * @Description: 定义一个任务之后进行触发设定
	 * @param sched:调度器
	 * @param time
	 * @param jobName:任务名
	 * @param jobGroupName:任务组名
	 */
	@SuppressWarnings("rawtypes")
	public static void addJObLaterUse(Scheduler sched, @SuppressWarnings("rawtypes") Class jobClass, String time,
			String jobName, String jobGroupName) {

		JobDetail job = newJob(jobClass).withIdentity(jobName, jobGroupName).storeDurably().build();

		try {
			sched.addJob(job, false);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description: 对已存储的任务进行scheduling(使用默认的任务组名,触发器名,触发器组名)
	 * @param sched:调度器
	 * @param time
	 * @param jobName:任务名
	 * @param jobGroupName:任务组名
	 */
	@SuppressWarnings("rawtypes")
	public static void schedulingStoredJOb(Scheduler sched, @SuppressWarnings("rawtypes") Class jobClass, String time) {
		schedulingStoredJOb(sched, jobClass, time, JOB_NAME, JOB_GROUP_NAME, TRIGGER_NAME, TRIGGER_GROUP_NAME);
	}

	/**
	 * @Description: 对已存储的任务进行scheduling
	 * @param sched:调度器
	 * @param time
	 * @param jobName:任务名
	 * @param jobGroupName:任务组名
	 */
	@SuppressWarnings("rawtypes")
	public static void schedulingStoredJOb(Scheduler sched, @SuppressWarnings("rawtypes") Class jobClass, String time,
			String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
		Trigger trigger = newTrigger().withIdentity(triggerName, triggerGroupName).startNow()
				.forJob(jobKey(jobName, jobGroupName)).build();
		try {
			sched.scheduleJob(trigger);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
	 * @param sched:调度器
	 * @param time
	 */
	@SuppressWarnings("rawtypes")
	public static void modifyJobTime(Scheduler sched, String time) {
		modifyJobTime(sched, TRIGGER_NAME, TRIGGER_GROUP_NAME, time);
	}

	/**
	 * @Description: 修改一个任务的触发时间
	 * @param sched:调度器
	 * @param triggerName
	 * @param triggerGroupName
	 * @param time
	 */
	public static void modifyJobTime(Scheduler sched, String triggerName, String triggerGroupName, String time) {
		Trigger trigger = newTrigger().withIdentity(triggerName, triggerGroupName).withSchedule(cronSchedule(time))
				.startNow().build();

		try {
			sched.rescheduleJob(triggerKey(triggerName, triggerGroupName), trigger);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description: 修改一个任务(使用默认的任务组名,任务名)
	 * @param sched:调度器
	 */
	@SuppressWarnings("rawtypes")
	public static void modifyJob(Scheduler sched, @SuppressWarnings("rawtypes") Class jobClass) {
		modifyJob(sched, jobClass, JOB_NAME, JOB_GROUP_NAME);
	}

	/**
	 * @Description: 修改一个任务
	 * @param sched:调度器
	 * @param jobName:任务名
	 * @param jobGroupName:任务组名
	 */
	public static void modifyJob(Scheduler sched, @SuppressWarnings("rawtypes") Class jobClass, String jobName,
			String jobGroupName) {
		JobDetail job1 = newJob(jobClass).withIdentity(jobName, jobGroupName).build();
		try {
			sched.addJob(job1, true);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description: 删除一个任务的的trigger
	 * @param sched:调度器
	 * @param triggerName
	 * @param triggerGroupName
	 */
	public static void unschedulingJob(Scheduler sched, String triggerName, String triggerGroupName) {
		try {
			sched.unscheduleJob(triggerKey(triggerName, triggerGroupName));
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description: 移除一个任务,以及任务的所有trigger
	 * @param sched:调度器
	 * @param jobName
	 */
	public static void removeJob(Scheduler sched, String jobName, String jobGroupName) {
		try {
			sched.deleteJob(jobKey(jobName, jobGroupName));
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description:启动所有定时任务
	 * @param sched:调度器
	 */
	public static void startJobs(Scheduler sched) {
		try {
			sched.start();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @Description:关闭所有定时任务
	 * @param sched:调度器
	 */
	public static void shutdownJobs(Scheduler sched) {
		try {
			if (!sched.isShutdown()) {
				// 未传参或false:不等待执行完成便结束;true:等待任务执行完才结束
				sched.shutdown();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

ServiceJob.java

package com.lbl.quartz.job;

import java.util.Date;

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

/**
 * 类说明:业务层
 * @author libl
 *
 */
public class ServiceJob implements Job{

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		//实现业务
		System.out.println(new Date());
	}
}

MasterScheduler.java

package com.lbl.quartz.scheduler;

import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;

import com.lbl.quartz.job.ServiceJob;
import com.lbl.quartz.utils.QuartzUtils;

/**
 * 类说明:总调度器
 * @author libl
 *
 */
public class MasterScheduler {
	public static void main(String[] args) throws Exception {
		Scheduler sched = new StdSchedulerFactory().getScheduler();
		sched.start();
		QuartzUtils.addJob(sched, ServiceJob.class, "0/1 * * * * ? ");
	}
}

运行结果
在这里插入图片描述

2.java web项目 Spring+Quartz启动 利用注解方式
项目结构
在这里插入图片描述
导入必备jar包
在这里插入图片描述
TestJob.java

package com.lbl.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
 * 类说明:启动项目后会自动执行
 * @author libaolei
 *
 */
@Component
public class TestJob {
	//@Scheduled这个注解,它可配置多个属性:如cron\fixedDelay\fixedRate
	@Scheduled(fixedDelay = 1000) // 一秒执行一次
	public void test() {
		System.out.println("job 开始执行" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	}
}

在这里插入图片描述

applicationContext.xml

<?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:aop="http://www.springframework.org/schema/aop"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:mvc="http://www.springframework.org/schema/mvc" 
	   xmlns:tx="http://www.springframework.org/schema/tx" 
	   xmlns:task="http://www.springframework.org/schema/task" 
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
	
    <!-- spring扫描注解的配置 -->
  	<context:component-scan base-package="com.lbl.quartz" />
  	
  	<!-- task:executor/@pool-size:可以指定执行线程池的初始大小、最大大小  -->
    <task:executor id="executor" pool-size="10"/>
    <!-- task:scheduler/@pool-size:调度线程池的大小,调度线程在被调度任务完成前不会空闲  -->
    <task:scheduler id="scheduler" pool-size="10"/>
    <!-- 定时器开关 开启这个配置,spring才能识别@Scheduled注解 -->
    <task:annotation-driven executor="executor" scheduler="scheduler"/>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>spring-quartz</display-name>
  
  <!-- 加载spring配置 -->
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- spring监听器 -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>

3.利用配置文件的方式
把配置文件写成这样,把TestJob注解去掉即可

  <?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:aop="http://www.springframework.org/schema/aop"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:mvc="http://www.springframework.org/schema/mvc" 
	   xmlns:tx="http://www.springframework.org/schema/tx" 
	   xmlns:task="http://www.springframework.org/schema/task" 
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
    
    <!-- 定时器开关-->
    <task:annotation-driven/>
    <!-- 管理的Bean -->
    <bean id="testJob" class="com.lbl.quartz.TestJob" />
    <task:scheduled-tasks scheduler="task">
        <!--每三秒执行一次  -->
     <task:scheduled ref="testJob" method="test"
            cron="0/1 * * * * ? " />
    </task:scheduled-tasks>
    <task:scheduler id="task" pool-size="10" />
    
</beans>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值