Spring task轻量级定时任务调度

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

【1】基于注解

我们可以使用@Scheduled注解进行开发,首先我们看下,该注解的源码

/*
 * Copyright 2002-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.scheduling.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation that marks a method to be scheduled. Exactly one of the
 * {@link #cron()}, {@link #fixedDelay()}, or {@link #fixedRate()}
 * attributes must be specified.
 *
 * <p>The annotated method must expect no arguments and have a
 * {@code void} return type.
 *
 * <p>Processing of {@code @Scheduled} annotations is performed by
 * registering a {@link ScheduledAnnotationBeanPostProcessor}. This can be
 * done manually or, more conveniently, through the {@code <task:annotation-driven/>}
 * element or @{@link EnableScheduling} annotation.
 *
 * @author Mark Fisher
 * @author Dave Syer
 * @author Chris Beams
 * @since 3.0
 * @see EnableScheduling
 * @see ScheduledAnnotationBeanPostProcessor
 * @see Schedules
 */
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {

	/**
	 * A cron-like expression, extending the usual UN*X definition to include
	 * triggers on the second as well as minute, hour, day of month, month
	 * and day of week.  e.g. {@code "0 * * * * MON-FRI"} means once per minute on
	 * weekdays (at the top of the minute - the 0th second).
	 * @return an expression that can be parsed to a cron schedule
	 * @see org.springframework.scheduling.support.CronSequenceGenerator
	 */
	String cron() default "";

	/**
	 * A time zone for which the cron expression will be resolved. By default, this
	 * attribute is the empty String (i.e. the server's local time zone will be used).
	 * @return a zone id accepted by {@link java.util.TimeZone#getTimeZone(String)},
	 * or an empty String to indicate the server's default time zone
	 * @since 4.0
	 * @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone)
	 * @see java.util.TimeZone
	 */
	String zone() default "";

	/**
	 * Execute the annotated method with a fixed period between the end
	 * of the last invocation and the start of the next.
	 * @return the delay in milliseconds
	 */
	long fixedDelay() default -1;

	/**
	 * Execute the annotated method with a fixed period between the end
	 * of the last invocation and the start of the next.
	 * @return the delay in milliseconds as a String value, e.g. a placeholder
	 * @since 3.2.2
	 */
	String fixedDelayString() default "";

	/**
	 * Execute the annotated method with a fixed period between invocations.
	 * @return the period in milliseconds
	 */
	long fixedRate() default -1;

	/**
	 * Execute the annotated method with a fixed period between invocations.
	 * @return the period in milliseconds as a String value, e.g. a placeholder
	 * @since 3.2.2
	 */
	String fixedRateString() default "";

	/**
	 * Number of milliseconds to delay before the first execution of a
	 * {@link #fixedRate()} or {@link #fixedDelay()} task.
	 * @return the initial delay in milliseconds
	 * @since 3.2
	 */
	long initialDelay() default -1;

	/**
	 * Number of milliseconds to delay before the first execution of a
	 * {@link #fixedRate()} or {@link #fixedDelay()} task.
	 * @return the initial delay in milliseconds as a String value, e.g. a placeholder
	 * @since 3.2.2
	 */
	String initialDelayString() default "";

}

可以看出该注解有五个方法或者叫参数,分别表示的意思是:

cron:指定cron表达式

zone:官方文档解释:A time zone for which the cron expression will be resolved。指定cron表达式运行的时区

fixedDelay:官方文档解释:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。

fixedRate:官方文档解释:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。

initialDelay:官方文档解释:Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.任务第一次被调用前的延时,单位毫秒

1.编写注解的定时任务类
package com.hikvision.energy.task;

import com.hikvision.energy.constant.InspectionConst;
import com.hikvision.energy.service.IInspectionService;
import com.hikvision.energy.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 智能巡检模块定时任务类
 *
 * @author wanjiadong
 * @description
 * @date Create in 0:23 2018/1/16
 */
@Component
public class InspectionHandleTask {

    //日志
    private static Logger log = LoggerFactory.getLogger(InspectionHandleTask.class);

    //巡检任务service
    @Autowired
    private IInspectionService inspectionService;

    /**
     * 每天定时(00:05:00)结束昨天及昨天之前的巡检任务
     *
     * @author wanjiadong
     * @date 2018/1/16 0:25
     * @params []
     * @return void
     */
    @Scheduled(cron = "0 5 0 * * ?")
    public void finishInspectionJob(){
        log.info("----finishInspectionJob begin------dateTime"+ DateUtils.getCurrentTime());
        try {
            //结束昨天及昨天之前的巡检任务
            inspectionService.endInspectionJob();
        } catch (Exception e) {
            log.error("finishInspectionJob error!", e.getMessage());
        }
    }
}

 2.在spring配置文件头中添加命名空间及描述(下面加粗处)并开启定时任务注解驱动

 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        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.2.xsd
         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
      
<!-- 开启这个配置,spring才能识别@Scheduled注解 -->
<task:executor id="executor" pool-size="5" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
</beans>


【2】基于配置文件
1.编写普通java class
package com.hafiz.www.cron;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Desc:第一个基于SpringTask的调度任务
 * Created by hafiz.zhang on 2016/12/11.
 */
public class FirstCron {
    private static final Logger logger = LoggerFactory.getLogger(FirstCron.class);

    public void cron() {
        logger.info("定时任务进行中.......");
        // do something else
    }
}
2.在spring配置文件头中添加命名空间及描述(下面加粗处)并配置定时任务
<beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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.2.xsd
       http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
 
     <bean id="firstCron" class="com.hafiz.www.cron.FirstCron"/>
     <task:scheduled-tasks>
         <task:scheduled ref="firstCron" method="cron" cron="0/5 * * * * ?"/>
     </task:scheduled-tasks>
 </beans>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

41摄氏度男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值