在项目中,有时会遇到定时任务的处理,下面介绍一下我的做法。

此做法基于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的定时任务管理的更多相关文章

  1. 基于PHP的crontab定时任务管理

    BY JENNER · 2014年11月10日· 阅读次数:6 linux的crontab一直是server运维.业务开展的利器.但当定时任务增多时,管理和迁移都变得非常麻烦,并且easy出问题.以下 ...

  2. 定时任务管理之python篇celery使用

    一.为什么要用celery celery是一个简单.灵活.可靠的,处理大量消息的分布式系统,并且提供维护这样一个系统的必须工具.他是一个专注于实时处理的任务队列,同时也支持任务调度. celery是异 ...

  3. Quartz 定时任务管理

    前言 将项目中的所有定时任务都统一管理吧,使用 quartz 定时任务 设计思路 使用 quartz 的相关jar 包,懒得去升级了,我使用的是 quart 1.6 写一个定时任务管理类 用一张数据库 ...

  4. 定时任务管理中心(dubbo+spring)-我们到底能走多远系列47

    我们到底能走多远系列47 扯淡: 又是一年新年时,不知道上一年你付出了多少,收获了多少呢?也许你正想着老板会发多少奖金,也许你正想着明年去哪家公司投靠. 这个时间点好好整理一下,思考总结一下,的确是个 ...

  5. SSM框架整合环境构建——基于Spring4和Mybatis3

    目录 环境 配置说明 所需jar包 配置db.properties 配置log4j.properties 配置spring.xml 配置mybatis-spring.xml 配置springmvc.x ...

  6. Linux编译安装、压缩打包、定时任务管理

    编译安装 压缩打包 定时任务管理 一.编译安装 使用源代码,编译打包软件 1.特点 1.可以定制软件 2.按需构建软件 2.编译安装 1.下载源代码包 wget https://nginx.org/d ...

  7. 基于Spring4+SpringMVC4+Mybatis3+Hibernate4+Junit4框架构建高性能企业级的部标GPS监控平台

    开发企业级的部标GPS监控平台,投入的开发力量很大,开发周期也很长,选择主流的开发语言以及成熟的开源技术框架来构建基础平台,是最恰当不过的事情,在设计之初就避免掉了技术选型的风险,避免以后在开发过程中 ...

  8. 基于Spring4+SpringMVC4+Mybatis3+Hibernate4+Junit4框架构建高性能企业级的部标1077视频监控平台

    开发企业级的部标GPS监控平台,投入的开发力量很大,开发周期也很长,选择主流的开发语言以及成熟的开源技术框架来构建基础平台,是最恰当不过的事情,在设计之初就避免掉了技术选型的风险,避免以后在开发过程中 ...

  9. 用abp vNext快速开发Quartz.NET定时任务管理界面

    今天这篇文章我将通过实例代码带着大家一步一步通过abp vNext这个asp.net core的快速开发框架来进行Quartz.net定时任务调度的管理界面的开发.大伙最好跟着一起敲一下代码,当然源码 ...

随机推荐

  1. wpf XAML xaml 进行 数据绑定,Resource DataContext ElementName

    先做个声明:这里绑定都在前台实现,至于后台怎么写,那比前台简单多了,但更常用的是xaml中绑定.我们分析下最简单的字符串绑定来弄清楚原理,其他的类推就是. 数据绑定主要是要弄清楚两个东西,一个是源So ...

  2. ASP.NET MVC5(二):控制器、视图与模型

    前言 本篇博文主要介绍ASP.NET MVC中的三个核心元素:控制器.视图与模型,以下思维导图描述了本文的主要内容. 控制器 控制器简介 在介绍控制器之前,简单的介绍一下MVC工作原理:URL告知路由 ...

  3. go 基础语法

    时间有限,简单记一些常用的,麻烦的不写了 定义变量:可以连续定义,也可以单个定义 var a int    int类型 var a="ds"   默认string类型 a:=&qu ...

  4. LoadRunner11_录制Oracle数据库脚本

    [oracle环境] ①oracle:无需在本地安装oracle,但是oracle的odbc驱动一定要装:(我的安装路径为 D:\oracle ).安装好后在环境变量 " Path &quo ...

  5. Linux文件锁定保护命令chattr介绍

    chattr命令的用法:chattr [ -RV ] [ -v version ] [ mode ] files- 最关键的是在[mode]部分,[mode]部分是由+-=和[ASacDdIijsTt ...

  6. v9.5.2上传缩略图/附件提示“undefined”

    把phpcms\modules\attachment\attachments.php中将                        if(empty($this->userid)){改成  ...

  7. C#继承的执行顺序

    自己对多态中构造函数.函数重载执行顺序和过程一直有些不理解,经过测试,对其中的运行顺序有了一定的了解,希望对初学者有些帮助. eg1: public class A { public A() { Co ...

  8. Linux中使用京东代码库JDCode创建私有Git仓库

    国外Git经常被墙,所以目光转向国内.目前,云存储真的是很热,有很多公司在做. 看了一下,CSDN,开源中国,淘宝,京东,Gitcafe都在搞.淘宝只支持SVN. JD号称提供1G免费空间,而且支持私 ...

  9. 【知识整理】这可能是最好的RxJava 2.x 教程(完结版)

    为什么要学 RxJava? 提升开发效率,降低维护成本一直是开发团队永恒不变的宗旨.近两年来国内的技术圈子中越来越多的开始提及 RxJava ,越来越多的应用和面试中都会有 RxJava ,而就目前的 ...

  10. Ext 常用组件解析

    Ext 常用组件解析 Panel 定义&常用属性 //1.使用initComponent Ext.define('MySecurity.view.resource.ResourcePanel' ...