Java web 定时任务

自己参考网上写了一下动态的定时任务
1.定时任务管理
import java.util.Map;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzManager {

 private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();  
 private static String JOB_GROUP_NAME = "LOAD_MODULE_DATA_JOBGROUP_NAME";           //加载组件数据任务组名称
 private static String TRIGGER_GROUP_NAME = "LOAD_MODULE_DATA_TRIGGERGROUP_NAME";   //加载组件数据触发器组名称

 /** 
  * 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名 
  */  
 public static void addJob(String jobName, Class cls, String time) {  
     try {  
         Scheduler sched = schedulerFactory.getScheduler();  
         JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, cls);// 任务名,任务组,任务执行类  
         // 触发器  
         CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);// 触发器名,触发器组  
         trigger.setCronExpression(time);// 触发器时间设定  
         sched.scheduleJob(jobDetail, trigger);  
         // 启动  
         if (!sched.isShutdown()) {  
             sched.start();  
         }  
     } catch (Exception e) {  
         throw new RuntimeException(e);  
     }  
 }  

 /** 
  * @Description: 添加一个定时任务 
  * @param jobName 任务名 
  * @param jobGroupName 任务组名 
  * @param triggerName 触发器名 
  * @param triggerGroupName 触发器组名 
  * @param jobClass 任务 
  */  
 public static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass, String time, Map paraMap) {  
     try {
         System.out.println("添加定时任务开始!");
         Scheduler sched = schedulerFactory.getScheduler();  
         JobDetail jobDetail = new JobDetail(jobName, jobGroupName, jobClass);// 任务名,任务组,任务执行类  
         jobDetail.getJobDataMap().putAll(paraMap);
         // 触发器  
         CronTrigger trigger = new CronTrigger(triggerName, triggerGroupName);// 触发器名,触发器组  
         trigger.setCronExpression(time);// 触发器时间设定  
         sched.scheduleJob(jobDetail, trigger);  
         System.out.println("添加定时任务结束!"+jobName);
         //sched.start();
     } catch (Exception e) {  
         throw new RuntimeException(e);  
     }  
 }  

 /** 
  * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名) 
  * @param jobName 
  * @param time 
  */  
 public static void modifyJobTime(String jobName, String time) {  
     try {  
         Scheduler sched = schedulerFactory.getScheduler();  
         CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName,TRIGGER_GROUP_NAME);  
         if (trigger == null) {  
             return;  
         }  
         String oldTime = trigger.getCronExpression();  
         if (!oldTime.equalsIgnoreCase(time)) {  
             JobDetail jobDetail = sched.getJobDetail(jobName,JOB_GROUP_NAME);  
             Class objJobClass = jobDetail.getJobClass();  
             removeJob(jobName);  
             addJob(jobName, objJobClass, time);  
         }  
     } catch (Exception e) {  
         throw new RuntimeException(e);  
     }  
 }  

 /** 
  * @Description: 修改一个任务的触发时间 
  *  
  * @param triggerName 
  * @param triggerGroupName 
  * @param time 
  */  
 public static void modifyJobTime(String triggerName, String triggerGroupName, String time) {  
     try {  
         Scheduler sched = schedulerFactory.getScheduler();  
         CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerName,triggerGroupName);  
         if (trigger == null) {  
             return;  
         }  
         String oldTime = trigger.getCronExpression();  
         if (!oldTime.equalsIgnoreCase(time)) {  
             CronTrigger ct = (CronTrigger) trigger;  
             // 修改时间  
             ct.setCronExpression(time);  
             // 重启触发器  
             sched.resumeTrigger(triggerName, triggerGroupName);  
         }  
     } catch (Exception e) {  
         throw new RuntimeException(e);  
     }  
 }  

 /** 
  * @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名) 
  * @param jobName 
  */  
 public static void removeJob(String jobName) {  
     try {  
         Scheduler sched = schedulerFactory.getScheduler();  
         sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME);   // 停止触发器  
         sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME);  // 移除触发器  
         sched.deleteJob(jobName, JOB_GROUP_NAME);          // 删除任务  
     } catch (Exception e) {  
         throw new RuntimeException(e);  
     }  
 }  

 /** 
  * @Description: 移除一个任务 
  * @param jobName 
  * @param jobGroupName 
  * @param triggerName 
  * @param triggerGroupName 
  */  
 public static void removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {  
     try {  
         Scheduler sched = schedulerFactory.getScheduler();  
         sched.pauseTrigger(triggerName, triggerGroupName); // 停止触发器  
         sched.unscheduleJob(triggerName, triggerGroupName);// 移除触发器  
         sched.deleteJob(jobName, jobGroupName);            // 删除任务  
     } catch (Exception e) {  
         throw new RuntimeException(e);  
     }  
 }  

 /** 
  * @Description:启动所有定时任务 
  */  
 public static void startJobs() {  
     try {  
         Scheduler sched = schedulerFactory.getScheduler(); 
         sched.start();  
         System.out.println("定时加载组件数据任务管理器启动!");
     } catch (Exception e) {  
         throw new RuntimeException(e);  
     }  
 }  

 /** 
  * @Description:关闭所有定时任务 
  */  
 public static void shutdownJobs() {  
     try {  
         Scheduler sched = schedulerFactory.getScheduler();  
         if (!sched.isShutdown()) {  
             sched.shutdown();  
             System.out.println("定时加载组件数据任务管理器关闭!");
         }  
     } catch (Exception e) {  
         throw new RuntimeException(e);  
     }  
 }  

}

2 定时任务执行方法的类
public class QuartzJob implements Job {

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    System.out.println("定时任务执行......"+DateUtil.getCurDateTimeFmt());
    /*JobDetail jobDetail = context.getJobDetail();
    JobDataMap map = jobDetail.getJobDataMap();
    FlowVO flowVO = (FlowVO)map.get("FlowVO");
    System.out.println(flowVO.getFlowCode());
    Thread thread = new Thread(new FlowRunTask(flowVO));
    thread.start();*/
}

}
3.测试定时任务
public class QuartzTest {

public static void main(String[] args) throws Exception {
    QuartzJobDO quartzJobDO = new QuartzJobDO();
    quartzJobDO.setQuartzCode("11111111111");
    quartzJobDO.setQuartzName("测试1");
    quartzJobDO.setQuartzTime(5);
    quartzJobDO.setQuartzUnit(Short.parseShort("0"));
    QuartzJobDO quartzJobDO1 = new QuartzJobDO();
    quartzJobDO1.setQuartzCode("qqwwww111111111");
    quartzJobDO1.setQuartzName("测试2");
    quartzJobDO1.setQuartzTime(1);
    quartzJobDO1.setQuartzUnit(Short.parseShort("1"));
    if("0".equals(quartzJobDO.getQuartzUnit().toString())){
        String cron = "0/"+quartzJobDO.getQuartzTime()+" * * * * ?"; 
        QuartzManager.addJob(quartzJobDO.getQuartzName(), QuartzJob.class, cron);
    }
    if("1".equals(quartzJobDO1.getQuartzUnit().toString())){
        System.out.println(quartzJobDO1.getQuartzName());
        String cron = "0/"+quartzJobDO1.getQuartzTime()+" * * * * ?"; 
        QuartzManager.addJob(quartzJobDO1.getQuartzName(), QuartzJob.class, cron);
    }
}

4.这是我自己写的一个quartzDO类,cron是确定是定时任务需要的时间表达式,这个需要自己拼

5.另外要启动执行的话需要自己写一个监听器,
public final class ApplicationStartListener implements ServletContextListener {

@Override
public void contextDestroyed(ServletContextEvent arg0) {
    //定时任务全部停止
    QuartzManager.shutdownJobs();
}

@Override
public void contextInitialized(ServletContextEvent event) {

    QuartzManager.startJobs();

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
    IQuartzJobService quartzJobService = (IQuartzJobService)context.getBean("quartzJobService");
    IFlowService flowService = (IFlowService)context.getBean("flowService");

    List list = quartzJobService.findAll();
    for (QuartzJobVO quartzJobVO : list) {
        HashMap paraMap = new HashMap();
        paraMap.put("FlowVO", flowService.findById(quartzJobVO.getFlowCode()));
        QuartzManager.addJob(quartzJobVO.getQuartzCode(), quartzJobVO.getJobGroupName(), quartzJobVO.getTriggerName(), quartzJobVO.getTriggerGroupName(), QuartzJob.class, quartzJobVO.getCronExp(), paraMap);
    }
}

}
6.在web.xml配置中,要放到spring监听之后

7.另外我这里是把定时任务具体化了,在数据库中有定时任务表

参考文章:http://blog.csdn.net/u012414587/article/details/50605861

你可能感兴趣的:(Java web 定时任务)