boot定时任务开启和关闭 spring_Spring Boot详解(3)定时任务

本文详细介绍了在Spring Boot中实现定时任务的方法,包括使用Timer和ScheduledExecutorService,Spring的配置定时任务和注解方式,以及基于接口的定时任务。特别讨论了Quartz的使用,包括CronTrigger和如何动态设置cron表达式。最后,提到了对Quartz的封装以简化配置。
摘要由CSDN通过智能技术生成

27b282c231e3d9d006e37ad85deed2b4.png
Spring Boot详解(3)定时任务​mp.weixin.qq.com
46071b2264565367d64d8501e49f6128.png

定时任务:我们在项目中,会使用定时任务去执行一些业务上或者是项目数据的备份和更新的操作,那么我们在微服务架构中怎么使用定时任务呢?又有多少种定时任务的实现方式呢?而定时任务的原理又是什么呢?


1. Timer 和 ScheduledExecutorService

Timer是jdk中提供的一个定时器工具,使用的时候会在主线程之外起一个单独的线程执行指定的计划任务,可以指定执行一次或者反复执行多次。但是不能指定时间运行,所以使用在使用场景上较为局限!

import java.util.Timer;
import java.util.TimerTask;
 
 public class TestTimer {
    
     
     public static void main(String args[]){
    
         System.out.println("About to schedule task.");
         new Reminder(3);
         System.out.println("Task scheduled.");
     }
     public static class Reminder{
    
         Timer timer;
         public Reminder(int sec){
    
             timer = new Timer();
             timer.schedule(new TimerTask(){
    
                public void run(){
    
                     System.out.println("Time's up!");
                     timer.cancel();
                 }
             }, sec*1000);
         }
     } 
 }

ScheduledExecutorService的主要作用就是可以将定时任务与线程池功能结合使用。

public class ScheduledExecutorServiceTest {
    
    public static void main(String[] args) {
    
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(new Runnable() {
    
            @Override
            public void run() {
    
                System.out.println("run "+ System.currentTimeMillis());
            }
        }, 0, 100, TimeUnit.MILLISECONDS);
    }
}

2.Spring 配置定时任务

在Spring中,通过Spring的配置文件进行注入定时任务的配置类,注入定时任务的执行类,通过标签定义。

xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation=" http://www.springframework.org/schema/task   
        http://www.springframework.org/schema/task/spring-task-3.0.xsd”
<description>
        定时任务
    </description>
    //定时注解驱动
    <task:annotation-driven />
    //进行定时任务的类,将其定义为一个bean
    <bean id="spaceStatisticsService" class="com.pojo.system.manager.sigar.impl.SpaceStatisticsServiceImpl"></bean>
    //通过task标签,定义定时功能
    <task:scheduled-tasks>
        <task:scheduled ref="spaceStatisticsService" method="statisticSpace" cron="59 59 23 * * ?" />
    </task:scheduled-tasks>

代码实现

@Service
public class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值