基于Spring4的定时任务管理
在项目中,有时会遇到定时任务的处理,下面介绍一下我的做法。
此做法基于Spring4,Spring框架搭建成功,另需引入quartz.jar,pom.xml文件中加入
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
创建基类,继承Job类
import org.quartz.Job;
import org.quartz.JobExecutionContext; public interface BaseJob extends Job{ @Override
public void execute(JobExecutionContext paramJobExecutionContext);
}
import org.quartz.JobExecutionContext;
public class BaseJobImpl implements BaseJob{
@Override
public void execute(JobExecutionContext paramJobExecutionContext){
}
}
创建两个要执行的定时任务类,继承BaseJobImpl 类
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Component; @Component
public class Job1 extends BaseJobImpl{ @Override
public void execute(JobExecutionContext paramJobExecutionContext){
System.out.println("定时任务1");
} }
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Component; @Component
public class Job2 extends BaseJobImpl{ @Override
public void execute(JobExecutionContext paramJobExecutionContext){
System.out.println("定时任务2");
}
}
创建定时任务管理类
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.quartz.JobDataMap;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; @Component
public class JobFactory {
private final Logger log = LogManager.getLogger(JobFactory.class);
private final static StdSchedulerFactory schedulerFactory = new StdSchedulerFactory ();
@Scheduled(cron = "*/10 * * * * ?")
public void run() throws SchedulerException{
//Job为一个Bean,对应数据库一张表,此处简单的做了两条假数据,真实项目应查询数据库表获得List
List<Job> list=new ArrayList<Job>();
Job job1=new Job();
job1.setFunctionName("execute");
job1.setGroupname("group1");
//此处Job1为定义的定时任务类,注意这里是类的路径,并不单纯是类名
job1.setJobClassName("Job1");
job1.setJobId("00000000000");
job1.setJobName("测试");
job1.setManagername("manager");
//此处为控制定时任务的执行,常见规则示例:
/**
每隔5秒执行一次:*/5 * * * * ?
每隔1分钟执行一次:0 */1 * * * ?
每天23点执行一次:0 0 23 * * ?
每天凌晨1点执行一次:0 0 1 * * ?
每月1号凌晨1点执行一次:0 0 1 1 * ?
每月最后一天23点执行一次:0 0 23 L * ?
每周星期天凌晨1点实行一次:0 0 1 ? * L
在26分、29分、33分执行一次:0 26,29,33 * * * ?
每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?
*/
job1.setRule("0/2 * * * * ?")
list.add(job1);
Job job2=new Job();
job2.setFunctionName("execute");
job2.setGroupname("group1");
job2.setJobClassName("Job2");
job2.setJobId("00000000001");
job2.setJobName("测试");
job2.setManagername("manager");
job2.setRule("0/2 * * * * ?"); list.add(job2);
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.clear();
for(int i=0;i<list.size();i++){
Job job=list.get(i);
System.out.println("任务管理"+i); try { String jobid=job.getJobId();
String functionName=job.getFunctionName();
String managerName=job.getManagername();
String classPath=job.getJobClassName();
if(jobid==null||jobid.equals("")||functionName==null||functionName.equals("")||managerName==null||managerName.equals("")||
classPath==null||classPath.equals("")){
log.info("==>Task Info ERROR.Can Not Create Task!");
return;
}
//启动任务
Object object=Class.forName(job.getJobClassName()).newInstance();
JobDetailImpl jobDetail = new JobDetailImpl(job.getJobId(), job.getGroupname(),
(Class<? extends BaseJobImpl>) object.getClass());
JobDataMap jobMap=new JobDataMap();
jobMap.put("managerName", managerName);
jobMap.put("functionName", functionName);
jobMap.put("taskid", jobid);
jobDetail.setJobDataMap(jobMap);
// 触发器
CronTriggerImpl trigger = new CronTriggerImpl(job.getJobId(), job.getGroupname());// 触发器名,触发器组
trigger.setCronExpression(job.getRule());
scheduler.scheduleJob(jobDetail, trigger);
// 启动
if (!scheduler.isShutdown()){
scheduler.start();
}else{
log.info("==>"+job.getJobName()+"["+job.getJobId()+"] is Shutdown");
}
} catch (Exception e) {
log.error("==>"+job.getJobName()+"["+job.getJobId()+"] Start ERROR");
log.error(job.getJobName()+"Start ERROR", e);
}
} } }
项目启动时上面的run方法要想启动,需要在spring配置文件中添加如下配置:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.1.xsd "> <task:annotation-driven executor="taskExecutor" scheduler="taskScheduler"/>
<task:executor id="taskExecutor" pool-size="5"/>
<task:scheduler id="taskScheduler" pool-size="10" /> </beans>
这样,由于run方法配置了@Scheduled(cron = "*/10 * * * * ?")注解,所以run方法会每隔十秒执行一次。
启动项目,结果如下:

这样就实现了定时任务的管理,如果你想写一个定时任务,只需要继承BaseJobImpl类,覆盖execute方法,并在数据库配置一条信息即可。
基于Spring4的定时任务管理的更多相关文章
- 基于PHP的crontab定时任务管理
BY JENNER · 2014年11月10日· 阅读次数:6 linux的crontab一直是server运维.业务开展的利器.但当定时任务增多时,管理和迁移都变得非常麻烦,并且easy出问题.以下 ...
- 定时任务管理之python篇celery使用
一.为什么要用celery celery是一个简单.灵活.可靠的,处理大量消息的分布式系统,并且提供维护这样一个系统的必须工具.他是一个专注于实时处理的任务队列,同时也支持任务调度. celery是异 ...
- Quartz 定时任务管理
前言 将项目中的所有定时任务都统一管理吧,使用 quartz 定时任务 设计思路 使用 quartz 的相关jar 包,懒得去升级了,我使用的是 quart 1.6 写一个定时任务管理类 用一张数据库 ...
- 定时任务管理中心(dubbo+spring)-我们到底能走多远系列47
我们到底能走多远系列47 扯淡: 又是一年新年时,不知道上一年你付出了多少,收获了多少呢?也许你正想着老板会发多少奖金,也许你正想着明年去哪家公司投靠. 这个时间点好好整理一下,思考总结一下,的确是个 ...
- SSM框架整合环境构建——基于Spring4和Mybatis3
目录 环境 配置说明 所需jar包 配置db.properties 配置log4j.properties 配置spring.xml 配置mybatis-spring.xml 配置springmvc.x ...
- Linux编译安装、压缩打包、定时任务管理
编译安装 压缩打包 定时任务管理 一.编译安装 使用源代码,编译打包软件 1.特点 1.可以定制软件 2.按需构建软件 2.编译安装 1.下载源代码包 wget https://nginx.org/d ...
- 基于Spring4+SpringMVC4+Mybatis3+Hibernate4+Junit4框架构建高性能企业级的部标GPS监控平台
开发企业级的部标GPS监控平台,投入的开发力量很大,开发周期也很长,选择主流的开发语言以及成熟的开源技术框架来构建基础平台,是最恰当不过的事情,在设计之初就避免掉了技术选型的风险,避免以后在开发过程中 ...
- 基于Spring4+SpringMVC4+Mybatis3+Hibernate4+Junit4框架构建高性能企业级的部标1077视频监控平台
开发企业级的部标GPS监控平台,投入的开发力量很大,开发周期也很长,选择主流的开发语言以及成熟的开源技术框架来构建基础平台,是最恰当不过的事情,在设计之初就避免掉了技术选型的风险,避免以后在开发过程中 ...
- 用abp vNext快速开发Quartz.NET定时任务管理界面
今天这篇文章我将通过实例代码带着大家一步一步通过abp vNext这个asp.net core的快速开发框架来进行Quartz.net定时任务调度的管理界面的开发.大伙最好跟着一起敲一下代码,当然源码 ...
随机推荐
- springmvc 添加@ResponseBody
1.添加ResponseBody之后的话 返回字符串的时候 就是一个字符串. @RequestMapping(value = "/{bookId}/detail.do",metho ...
- 启动 Eclipse 弹出“Failed to load the JNI shared library jvm.dll”的解决方法!
原因:eclipse的版本与jre或者jdk版本不一致 对策:要么两者都安装64位的,要么都安装32位的,不能一个是32位一个是64位. 这种错误的原因可能性比较大,不排除其他因素
- Deep Q-Network 学习笔记(一)—— Q-Learning 学习与实现过程中碰到的一些坑
这方面的资料比较零散,学起来各种碰壁,碰到各种问题,这里就做下学习记录. 参考资料: https://morvanzhou.github.io/ 非常感谢莫烦老师的教程 http://mnemstud ...
- JDK和Tomcat的简单配置(菜鸟巧记一)
JDK和Tomcat的配置 1.先好安装JDK 1.1先到oracle官网下载合适自己的JDK 地址http://www.oracle.com/technetwork/java/javase/down ...
- PO/VO/POJO/BO/VO图解
- Lucence_Curd
设置Field的类型 new StringField 不分词(id,身份证号,电话...) new StoredField 不分词(链接) new TextField 分词(文本) new Fload ...
- 总结一下最近用过的phpcms语法
到目前为止用到过的phpcms语法: 1.取栏目名称: {category[$catid][catname]} 2.取栏目地址: {category[14][url]} 3.取一级栏目: {pc:co ...
- php提示php_network_getaddresses: getaddrinfo failed: Name or service not known
php_network_getaddresses: getaddrinfo failed: Name or service not known 面对这个错误,已经相对熟悉了.想起来应该是服务器无法访问 ...
- php通过cURL下载网络上面的一个HTTPS的资源
<?php /** * php通过cURL下载网络上面的一个HTTPS的资源 * 案例:从google的CDN上下载jquery- v1.7.1 */ $curlobj = curl_init( ...
- 【LeetCode】136. Single Number
题目: Given an array of integers, every element appears twice except for one. Find that single one. No ...