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

此做法基于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经典编程题50道之三十三

    打印出杨辉三角形(要求打印出10行如下图)11 11 2 11 3 3 11 4 6 4 11 5 10 10 5 1 public class Example33 { public static v ...

  2. NodeMCU入门(2):在线构建、刷入固件,上传代码

    准备工作 1.NodeMCU模块 2.ESP8266Flasher.exe 3.ESPlorer v0.2.0-rc6 构建固件 Building the firmware提供了三种构建你自己固件的方 ...

  3. 仿flash轮播

    <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title> ...

  4. Context源码分析

    我们做安卓开发,时时都在和Context打交道,那么Context到底是什么?有什么作用?如何与Application,Activity,Service等实例发生联系的?等等 Context是什么? ...

  5. Bash内置命令exec和重定向

    Bash内置命令exec可以替换当前程序而不需要启动一个新的进程,可以改变标准输入和输出而不需要启动一个新的子进程.如果文件用exec打开,read命令就会把文件指针每次指向下一行直到文件的末尾,如果 ...

  6. 小试牛刀JavaScript鼠标事件

    鼠标事件练习1 当鼠标点击网页某个单元格的时候,其他的单元格颜色不变,只有被点击的单元格颜色发生变化 <style type="text/css"> *{ margin ...

  7. 使用ConfuserEx加密混淆程序以及如何脱壳反编译

    一,准备如下工具: ConfuserEx.UnConfuserEx.Fixer.ConfuserExStringDecryptor.ConfuserExSwitchKiller.de4dot.ILSp ...

  8. SDS 链表

    sds定义 struct sdshdr{ int len int free char buf[] } sds和c语言类似,仍然把字符串的末尾加上一个'.0',但是不会计入总长度,也就是不会对len造成 ...

  9. 【LeetCode】219. Contains Duplicate II

    题目: Given an array of integers and an integer k, find out whether there are two distinct indices i a ...

  10. 2.如何搭建MQTT环境

    1.源码下载https://github.com/andsel/moquette 注意下载2016.2版本2.idea下载http://confluence.jetbrains.com/display ...