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

此做法基于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. Java内存管理思维导图

    文 by / 林本托 Tips 做一个终身学习的人. 如果想要成为一名合格的 Java 程序员,就必须要涉及和掌握一些 Java 虚拟机的内部结构和特性.最近在读<深入理解Java 虚拟机> ...

  2. Gradle入门学习---认识buildeTypes和dependencies

    Gradle是Android Studio默认的构建工具,如果是基本的APP开发,不会涉及到Gradle太多内容,毕竟它的诞生就不是专为Android服务的. 日常开发需要涉及到使用Gradle的场景 ...

  3. xshell连接ubuntu

    安装了 ubuntu-14 ,为了连接 xshell ,做出的一些配置如下: 1.激活root用户 sudo passwd root 设置新密码,设置成功后会有提示 passwd:password u ...

  4. 警告: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:JsonBlog' did not find a matching property.

    这个问题困扰很久了,逛了很多论坛,终于得以解决 我的控制台错误如下: 五月 , :: 下午 org.apache.catalina.startup.VersionLoggerListener log ...

  5. (转)java web 学习之路(学习顺序)

    第一步:学习HTML和CSS HTML(超文本标记语言)是网页的核心,学好HTML是成为Web开发人员的基本条件.HTML很容易学习的,但也很容易误用,要学精还得费点功夫. 随着HTML5的发展和普及 ...

  6. if中可以使用那些作为判断条件呢?

    在所有编程语言中if是最长用的判断之一,但在js中到底哪些东西可以在if中式作为判断表达式呢? 例如如何几行,只是少了一个括号,真假就完全不同,到底表示什么含义呢 ? 1 2 3 4 5 6 7 8 ...

  7. 快速压缩PNG文件在线工具

    https://tinypng.com/ 直接拖移要压缩文件即可

  8. arcgis api for js入门开发系列十一地图统计图

    上一篇实现了demo的叠加SHP图层,本篇新增地图统计图,截图如下: 地图统计图实现的思路如下:利用拓展arcgis api的js文件(MapChartGraphic.js以及MapChartGrap ...

  9. C# 微信 企业号通知消息

    每当有个Create 事件,要通知相关的人员. 1.扫码登录企业微信,到企业应用. 2.获取微信配置信息. Secret和AgentId. 3.管理通讯录,配置接收消息的人群.可以按照部门,标签.获取 ...

  10. 【CC2530入门教程-03】CC2530的中断系统及外部中断应用

    第3课  CC2530的中断系统及外部中断应用 广东职业技术学院  欧浩源 一.中断相关的基础概念  内核与外设之间的主要交互方式有两种:轮询和中断. 轮询的方式貌似公平,但实际工作效率很低,且不能及 ...