Spring Task 定时器

1、介绍

Spring Task,可以把它看成轻量级的 Quartz,使用简单方便,也同样支持注解和配置文件两种形式,除此之外,还会额外介绍一种方式:通过前台操作调用 RESTful 执行定时任务的调度,下面,我将分别介绍。

2、定时任务开发步骤

2.1 基于配置文件
  • 编写配置文件
package com.hafiz.www.cron;

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

/**
 * Desc:第一个基于SpringTask的调度任务
 */
 public class FirstCron {
    private static final Logger logger = LoggerFactory.getLogger(FirstCron.class);

    public void cron() {
        logger.info("定时任务进行中.......");
        // do something else    
    }
}
  • 在 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>

设置每 5 秒钟执行一次。

2.2 基于注解

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

 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;
 import org.springframework.scheduling.annotation.Schedules;
 
 @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
 @Retention(RetentionPolicy.RUNTIME)
 @Documented
 @Repeatable(Schedules.class)
 public @interface Scheduled {
     String cron() default "";
 
     String zone() default "";
 
     long fixedDelay() default -1L;
 
     String fixedDelayString() default "";
 
     long fixedRate() default -1L;
 
     String fixedRateString() default "";
 
     long initialDelay() default -1L;
 
     String initialDelayString() default "";
 }

该注解有 5 个参数,分别表示的意思是:

  • 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.hafiz.www.cron;

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

/**
 * Desc:第一个基于SpringTask的调度任务
 */
 public class FirstCron {
    private static final Logger logger = LoggerFactory.getLogger(FirstCron.class);

    @Scheduled(cron = "0/5 * * * * ?")
    public void cron() {
        logger.info("定时任务进行中.......");
        // do something else    
    }

}
  1. 在配置文件中添加
<task:annotation-driven/>

完成这两步即可。

2.3 通过调用 RESTful 执行定时任务的调度,使用一下 Controller 即可。
package com.louis.merak.common.schedule;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MerakTaskSchedulerController {
    
    @Autowired
    MerakTaskScheduler taskScheduler;
    
    @RequestMapping("/schedule")
    public String schedule(@RequestParam String cron) {
     if(cron == null) {
       cron = "0/5 * * * * *";
        }
        Runnable runnable = new Runnable() {
            public void run() {
                String time = new SimpleDateFormat("yy-MM-dd HH:mm:ss").format(new Date());
                System.out.println("Test GETaskScheduler Success at "  + time);
            }
        };

        taskScheduler.schedule(runnable, cron);
        return "Test TaskScheduler Interface.";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值