spring任务调度 注解+配置文件

本文介绍Spring3.0以后自主开发的定时任务工具,spring task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种形式,下面将分别介绍这两种方式。

1.配置文件方式

package com.htf.task;

public class MyTask {
	
	public void say(){
		
		System.out.println("xml配置方式--调用定时任务成功。。。");
	}

}
2.注解方式

package com.htf.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyTaskAnnotation {
	
	 /**  
     * 定时计算。每天凌晨 01:00 执行一次  
     */    
    @Scheduled(cron="5/3 * * * * ?")  
    public void show(){  
        System.out.println("Annotation:is show run 注解 定时计算任务");  
    }  
    
    /**  
     * 心跳更新。启动时执行一次,之后每隔2秒执行一次  
     */    
    @Scheduled(fixedRate = 1000*10)   
    public void print(){  
        System.out.println("Annotation:print run 注解 心跳更新任务");  
    }  
}
springmvc-servlet.xml   配置文件写在了一起。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:task="http://www.springframework.org/schema/task" 
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

	<!-- @Controller, @Service, @Configuration, etc. -->
	<context:component-scan base-package="com.htf.controller" />

	
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- set the max upload size100MB -->
		<property name="maxUploadSize">
			<value>104857600</value>
		</property>
		<property name="maxInMemorySize">
			<value>4096</value>
		</property>
	</bean>
<!-- 注解方式springTask -->
	<task:annotation-driven/>
	
	<context:component-scan base-package="com.htf.task" /><!-- 自动扫描 -->
<!-- 注解方式springTask -->

<!-- 配置方式springTask -->
	<!-- <bean id="taskTest" class="com.htf.task.MyTask"></bean>
	<task:scheduled-tasks>
		  <task:scheduled ref="taskTest" method="say" cron="5/3 * * * * ?" />  
	</task:scheduled-tasks> -->
	
</beans>

cron 表达式配置  http://cron.qqe2.com/

动态配置Job

import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class JobManager {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    private static final String JOB_DATA_MAP="JOB_DATA_MAP";

    public void scheduleJob(JobConfig job) throws Exception {
        JobKey jobKey = new JobKey(job.getJobName(), job.getJobGroup());
        boolean existed = schedulerFactoryBean.getScheduler().checkExists(jobKey);
        if (existed) {
            JobDetail jobDetail = schedulerFactoryBean.getScheduler().getJobDetail(jobKey);
            JobConfig JobConfig = (JobConfig) jobDetail.getJobDataMap().get(JOB_DATA_MAP);
            if (JobConfig.getJobCronExpress().equals(job.getJobCronExpress())) {
                return;
            }
            removeJob(job);
        }
        Class clazz = Class.forName(job.getJobClass());
        JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(job.getJobName(), job.getJobGroup()).build();
        jobDetail.getJobDataMap().put(JOB_DATA_MAP, job);
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getJobCronExpress());
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup()).withSchedule(scheduleBuilder).build();
        schedulerFactoryBean.getScheduler().scheduleJob(jobDetail, trigger);
    }

    public void rescheduleJob(JobConfig job) throws Exception {
        if (!checkJobExisted(job)) {
            scheduleJob(job);
        }
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
        CronTrigger trigger = (CronTrigger) schedulerFactoryBean.getScheduler().getTrigger(triggerKey);
        if (!trigger.getCronExpression().equals(job.getJobCronExpress())) {
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getJobCronExpress());
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            JobDetail jobDetail = schedulerFactoryBean.getScheduler().getJobDetail(trigger.getJobKey());
            jobDetail.getJobDataMap().put(JOB_DATA_MAP, job);
            schedulerFactoryBean.getScheduler().rescheduleJob(triggerKey, trigger);
        }
    }

    public void pauseJob(JobConfig job) throws Exception {
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        if (!schedulerFactoryBean.getScheduler().checkExists(jobKey)) {
            scheduleJob(job);
        }
        schedulerFactoryBean.getScheduler().pauseJob(jobKey);
    }

    public void resumeJob(JobConfig job) throws Exception {
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        if (!schedulerFactoryBean.getScheduler().checkExists(jobKey)) {
            scheduleJob(job);
        }
        schedulerFactoryBean.getScheduler().resumeJob(jobKey);
    }

    public void removeJob(JobConfig job) throws Exception {
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        if (!schedulerFactoryBean.getScheduler().checkExists(jobKey)) {
            scheduleJob(job);
        }
        schedulerFactoryBean.getScheduler().deleteJob(jobKey);
    }

    public boolean checkJobExisted(JobConfig job) throws Exception {
        return schedulerFactoryBean.getScheduler().checkExists(new JobKey(job.getJobName(), job.getJobGroup()));
    }

    public List<JobConfig> getRunningJobs() throws Exception {
        List<JobExecutionContext> runningJobs = schedulerFactoryBean.getScheduler().getCurrentlyExecutingJobs();
        List<JobConfig> jobList = new ArrayList<JobConfig>(runningJobs.size());
        for (JobExecutionContext executingJob : runningJobs) {
            JobConfig job = new JobConfig();
            JobDetail jobDetail = executingJob.getJobDetail();
            JobKey jobKey = jobDetail.getKey();
            job.setJobName(jobKey.getName());
            job.setJobGroup(jobKey.getGroup());
            jobList.add(job);
        }
        return jobList;
    }

    public List<JobConfig> scheduleJobs() throws Exception {
        List<JobConfig> jobList = new ArrayList<JobConfig>();
        GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
        Set<JobKey> jobKeys = schedulerFactoryBean.getScheduler().getJobKeys(matcher);
        for (JobKey jobKey : jobKeys) {
            JobConfig job = new JobConfig();
            job.setJobName(jobKey.getName());
            job.setJobGroup(jobKey.getGroup());
            jobList.add(job);
        }
        return jobList;
    }
}

job类

public class JobConfig implements Serializable{

    private Integer id;
    private String  jobName;
    private String  jobGroup;
    private String  jobClass;
    private String  jobStatus;
    private String  jobCronExpress;
    ......
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值