spring定时任务的用法(可以用)

Spring Task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种.

一、XML配置文件方式

编写作业类

就是即普通的Java类,如下, 

  •  定时任务1
import java.text.SimpleDateFormat;
import java.util.Date;

public class TaskJob {
     //定时执行代码块
    public void myMethod() {
        System.out.println((new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(new Date())+ " 我是后台任务1...");
    }
} 
  • 定时任务2
import java.text.SimpleDateFormat;
import java.util.Date;


public class TaskJob2 {
    //定时任务代码块
	public void myMethod() {
        System.out.println((new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(new Date())+ " 我是后台任务2...");
    }
}

在spring配置文件头中添加命名空间及描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="  
        http://www.springframework.org/schema/task 
        http://www.springframework.org/schema/task/spring-task-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">
</beans>

 spring配置文件中设置具体的任务(与上面代码是在同一个xml中)

<!-- 定时任务要执行的方法 -->
<bean id="taskJob" class="com.task.TaskJob" />
<bean id="taskJob2" class="com.task.TaskJob2" />

<!--用于定时任务的执行 -->
<task:scheduled-tasks>
    <!-- 指定要运行的类的方法,每2秒执行一次 -->
    <task:scheduled ref="taskJob" method="myMethod" cron=" 0/2 * * * * ?" />
    <!-- 指定要运行的类的方法,每3秒执行一次 -->
    <task:scheduled ref="taskJob2" method="myMethod" cron=" 0/3 * * * * ?" />
</task:scheduled-tasks>

二、注解的方式

注解@Scheduled的定义

@Target({java.lang.annotation.ElementType.METHOD,java.lang.annotation.ElementType.ANNOTATION_TYPE})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface Scheduled  
{  
  public abstract String cron();  

  public abstract long fixedDelay();  

  public abstract long fixedRate();  
} 

可以看出该注解有三个方法或者叫参数,分别表示的意思是: 
* cron:指定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.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。

编写pojo
 

import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component("taskJob")
public class TaskJob {

    @Scheduled(cron = " 0/2 * * * * ?") // 每两秒执行一次
    public void myMethod() {
        System.out.println(new Date().toLocaleString() + " 我是基于注解的后台任务...");
    }
}

添加task相关的配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="  
        http://www.springframework.org/schema/task 
        http://www.springframework.org/schema/task/spring-task-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">

    <context:annotation-config />
    <!-- spring扫描注解的配置 -->
    <context:component-scan base-package="com.antation" />

    <!-- 开启这个配置,spring才能识别@Scheduled注解 -->
    <task:annotation-driven scheduler="qbScheduler" mode="proxy" />
    <task:scheduler id="qbScheduler" pool-size="10" />

</beans>

 

说明:理论上只需要加上这句配置就可以了,这些参数都不是必须的。

三、Java测试程序

import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnationTaskTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext-task.xml");
        //try catch可以不写
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果

2018-10-18 10:48:50 我是后台任务1...
2018-10-18 10:48:51 我是后台任务2...
2018-10-18 10:48:52 我是后台任务1...
2018-10-18 10:48:54 我是后台任务2...
2018-10-18 10:48:54 我是后台任务1...
2018-10-18 10:48:56 我是后台任务1...
2018-10-18 10:48:57 我是后台任务2...
2018-10-18 10:48:58 我是后台任务1...

原文链接:https://blog.csdn.net/zbw18297786698/article/details/73438014

注意:以上只需要Spring的jar包和3个必须jar包,方可运行(网上下载即可)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring 定时任务Spring 框架提供的一种定时执行任务的方法,可以在指定的时间间隔或者指定的时间点,执行某个任务。Spring 定时任务的实现依赖于 Spring 自带的 TaskExecutor、TaskScheduler 和 Cron 表达式。 Spring 定时任务的步骤如下: 1. 在配置文件中配置 TaskExecutor 或 TaskScheduler。 2. 创建一个带有 @Scheduled 注解的方法,指定该方法的执行时间或时间间隔。 3. 启动应用程序。 4. Spring 定时任务会自动执行指定时间或时间间隔的方法。 下面是一个简单的 Spring 定时任务的示例: ```java @Component public class MyTask { @Scheduled(fixedRate = 1000) // 每隔 1 秒执行一次 public void task() { System.out.println("定时任务执行中..."); } } ``` 在上面的代码中,我们使用 @Scheduled 注解来标记一个定时执行的方法,并指定了该方法执行的时间间隔为 1 秒。需要注意的是,使用 @Scheduled 注解的类必须被 Spring 扫描到,可以通过 @Component 标记该类。 除了使用 fixedRate 属性来指定执行时间间隔之外,@Scheduled 注解还有其他属性可以使用,例如 fixedDelay、initialDelay 和 cron 等,可以根据实际需求灵活配置。 在配置 TaskExecutor 或 TaskScheduler 时,可以选择使用 Spring 自带的 ThreadPoolTaskExecutor 和 ConcurrentTaskScheduler,也可以自定义实现。需要注意的是,如果使用默认的线程池和任务调度器,需要在配置文件中添加 @EnableScheduling 注解才能生效。 以上就是 Spring 定时任务的基本使用方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值