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

此做法基于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. 各种Web漏洞测试平台

    Sqli Lab​支持报错注入.二次注入.盲注.Update注入.Insert注入.Http头部注入.二次注入练习等.支持GET和POST两种方式. https://github.com/Audi-1 ...

  2. vue.js实现数据动态响应(Vue.set的应用)

    在vue里面,我们操作最多的就是各种数据,在jquery里面,我们习惯通过下标定向找到数据,然后重新赋值 比如var a[0]=111;(希望上家公司原谅菜鸟的我写了不少这样的代码

  3. 锁和监视器之间的区别 – Java并发

    在面试中你可能遇到过这样的问题:锁(lock)和监视器(monitor)有什么区别? 嗯,要回答这个问题,你必须深入理解Java的多线程底层是如何工作的. 简短的答案是,锁为实现监视器提供必要的支持. ...

  4. EntityFramework Core映射关系详解

    前言 Hello,开始回归开始每周更新一到两篇博客,本节我们回归下EF Core基础,来讲述EF Core中到底是如何映射的,废话少说,我们开始. One-Many Relationship(一对多关 ...

  5. java 字符串全排列 和 去重

    用递归进行排序 , 用TreeSet 去重. public class test { public static void main(String []args){ String str = &quo ...

  6. python网络爬虫之使用scrapy自动爬取多个网页

    前面介绍的scrapy爬虫只能爬取单个网页.如果我们想爬取多个网页.比如网上的小说该如何如何操作呢.比如下面的这样的结构.是小说的第一篇.可以点击返回目录还是下一页 对应的网页代码: 我们再看进入后面 ...

  7. linux使用crontab实现PHP执行定时任务

    首先说说cron,它是一个linux下的定时执行工具.根用户以外的用户可以使用 crontab 工具来配置 cron 任务. 所有用户定义的 crontab 都被保存在/var/spool/cron ...

  8. 【Android Developers Training】 53. 打印HTML文档

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  9. 3.sublime vue 语法高亮插件安装

    默认情况下,Vue.js 的单文件组件(*.vue)在 sublime 编辑器中是不被识别的.若要想高亮显示,需要安装插件 Vue Syntax Hightlight.安装步骤如下:   第一,在 s ...

  10. Error detected while processing function CheckFoam256 问题的解决

    今天在打开OpenFOAM的constant文件的时候, vim-OpenFOAM-syntax插件遇到了如下问题: Error detected while processing function ...