iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >在springboot中使用定时任务的方式
  • 485
分享到

在springboot中使用定时任务的方式

2023-06-20 12:06:13 485人浏览 泡泡鱼
摘要

本篇内容介绍了“在SpringBoot中使用定时任务的方式”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!springboot定时任务在spr

本篇内容介绍了“在SpringBoot中使用定时任务的方式”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

springboot定时任务

在springboot环境下有多种方法,这里记录下使用过的其中两种;1、使用注解,2、通过实现接口的方式。

使用注解的方式虽然比较简单,但是如果项目需要用户对定时周期进行修改操作,只使用注解就比较难实现。所以可以使用实现接口的方式。通过对接口的实现,可以在项目运行时根据需要修改任务执行周期,只需要关闭原任务再开启新任务即可。

1、使用注解方式

首先需要在启动类下添加 @EnableScheduling 注解(@EnableAsync是开启异步的注解)

package com.fongtech.cli; import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication@MapperScan("com.fongtech.cli.mbg.*.**")@EnableAsync@EnableScheduling public class SpringbootAdminApplication {     public static void main(String[] args) {        SpringApplication.run(SpringbootAdminApplication.class, args);    } }

接着在需要用到定时任务的类和方法下加 @Component 和 @Scheduled(cron = "0 0/1 * * * ? ")注解,其中@Scheduled()中的 ‘cron' 有固定的格式。(@Async注解表示开启异步)

@Slf4j@Componentpublic class AsyncTaskConfiguration {         @Scheduled(cron = "0 0/1 * * * ? ")    @Async    public void startCommonTask() throws Exception {        log.info("startCommonTask  start........." + Thread.currentThread().getName());        commonTaskService.startCommonTask();        log.info("startCommonTask  end........." + Thread.currentThread().getName());     }}

2、使用实现接口的方式

通过实现 SchedulinGConfigurer 接口,可对定时任务进行操作。实现接口的方式相比使用注解更加灵活,但需要编写代码,相对繁琐。

实现工具类如下:

package com.fongtech.cli.admin.tasktime; import com.fongtech.cli.common.util.BeanUtils;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.SchedulingException;import org.springframework.scheduling.TaskScheduler;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.SchedulingConfigurer;import org.springframework.scheduling.config.ScheduledTaskReGIStrar;import org.springframework.scheduling.config.TriggerTask;import org.springframework.scheduling.support.CronTrigger; import javax.annotation.PostConstruct;import java.util.Map;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ScheduledFuture; @Configuration//@EnableSchedulingpublic class DefaultSchedulingConfigurer implements SchedulingConfigurer {    private ScheduledTaskRegistrar taskRegistrar;    private Set<ScheduledFuture<?>> scheduledFutures = null;    private Map<String, ScheduledFuture<?>> taskFutures = new ConcurrentHashMap<>();     @Override    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {        this.taskRegistrar = taskRegistrar;    }     @SuppressWarnings("unchecked")    private Set<ScheduledFuture<?>> getScheduledFutures() {        if (scheduledFutures == null) {            try {                // spring版本不同选用不同字段scheduledFutures                scheduledFutures = (Set<ScheduledFuture<?>>) BeanUtils.getProperty(taskRegistrar, "scheduledTasks");            } catch (NoSuchFieldException e) {                throw new SchedulingException("not found scheduledFutures field.");            }        }        return scheduledFutures;    }         public void addTriggerTask(String taskId, TriggerTask triggerTask) {        if (taskFutures.containsKey(taskId)) {            throw new SchedulingException("the taskId[" + taskId + "] was added.");        }        TaskScheduler scheduler = taskRegistrar.getScheduler();        ScheduledFuture<?> future = scheduler.schedule(triggerTask.getRunnable(), triggerTask.getTrigger());        getScheduledFutures().add(future);        taskFutures.put(taskId, future);    }         public void cancelTriggerTask(String taskId) {        ScheduledFuture<?> future = taskFutures.get(taskId);        if (future != null) {            future.cancel(true);        }        taskFutures.remove(taskId);        getScheduledFutures().remove(future);    }         public void resetTriggerTask(String taskId, TriggerTask triggerTask) {        cancelTriggerTask(taskId);        addTriggerTask(taskId, triggerTask);    }         public Set<String> taskIds() {        return taskFutures.keySet();    }         public boolean hasTask(String taskId) {        return this.taskFutures.containsKey(taskId);    }         public boolean inited() {        return this.taskRegistrar != null && this.taskRegistrar.getScheduler() != null;    }}

在项目启动后就自动开启任务的操作类如下:

package com.fongtech.cli.admin.tasktime; import com.fongtech.cli.admin.service.IAuthLoginService;import com.fongtech.cli.admin.service.IBackupsService;import com.fongtech.cli.admin.service.IDictionnaryEntryService;import com.fongtech.cli.mbg.model.entity.AuthLogin;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.core.annotation.Order;import org.springframework.scheduling.config.TriggerTask;import org.springframework.scheduling.support.CronTrigger;import org.springframework.stereotype.Component; @Slf4j@Component@Order(value = 1)public class CmdRunner implements CommandLineRunner {     @Autowired    private DefaultSchedulingConfigurer defaultSchedulingConfigurer;    @Autowired    private IDictionnaryEntryService dictionnaryEntryService;    @Autowired    private IBackupsService backupsService;    @Autowired    private IAuthLoginService authLoginService;     @Override    public void run(String... args) throws Exception {        log.info("------按照预设备份周期启动数据库备份定时任务");        while (!defaultSchedulingConfigurer.inited())        {            try {                Thread.sleep(100);            } catch (InterruptedException e) {                e.printStackTrace();            } finally {             }        }        String cron = dictionnaryEntryService.getEntryValueByName("CRON_VALUE");        //默认按照管理员用户权限执行备份任务        AuthLogin authLogin = authLoginService.query().eq(AuthLogin::getLogin_user, "admin").getOne();        //启动线程,按照原表内的时间执行备份任务        defaultSchedulingConfigurer.addTriggerTask("task",                new TriggerTask(                        () -> System.out.println("=====----------启动定时任务=-----------");,                        new CronTrigger(cron)));    }}

暂停定时任务:

defaultSchedulingConfigurer.cancelTriggerTask("task");

“在springboot中使用定时任务的方式”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!

--结束END--

本文标题: 在springboot中使用定时任务的方式

本文链接: https://www.lsjlt.com/news/296558.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 在springboot中使用定时任务的方式
    本篇内容介绍了“在springboot中使用定时任务的方式”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!springboot定时任务在spr...
    99+
    2023-06-20
  • 浅谈在springboot中使用定时任务的方式
    springboot定时任务 在springboot环境下有多种方法,这里记录下使用过的其中两种;1、使用注解,2、通过实现接口的方式。 使用注解的方式虽然比较简单,但是如果项目需要...
    99+
    2024-04-02
  • SpringBoot中怎么使用定时任务
    本篇文章为大家展示了SpringBoot中怎么使用定时任务,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1. 线程实现利用线程可以设定休眠时间的方式可以实现简单的定时任务逻辑。  ...
    99+
    2023-06-02
  • SpringBoot定时任务怎么使用
    在Spring Boot中使用定时任务,可以按照以下步骤进行操作:1. 在pom.xml文件中添加Spring Boot的定时任务依...
    99+
    2023-08-15
    SpringBoot
  • Python使用定时调度任务的方式
    目录1、简单循环 Simple loops2、简单循环但是使用了线程Simple loops but threaded3、定时调度库 Schedule Library4、Python...
    99+
    2024-04-02
  • SpringBoot中使用@scheduled定时执行任务的坑
    目录解决办法1.将@Scheduled注释的方法内部改成异步执行2.把Scheduled配置成成多线程执行要注意什么坑 不绕弯子了,直接说这个坑是啥: SpringBoot使用@sc...
    99+
    2024-04-02
  • 如何在SpringBoot中配置ShedLock分布式定时任务
    本篇文章为大家展示了如何在SpringBoot中配置ShedLock分布式定时任务,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。什么是ShedLockShedLock是一个在分布式环境中使用的定时任...
    99+
    2023-06-15
  • springboot实现定时任务的四种方式小结
    目录TimerScheduledExecutor注解@ScheduledQuartz因为某些需求,要在特定的时间执行一些任务,比如定时删除服务器存储的数据缓存,定时获取数据以及定时发...
    99+
    2023-01-13
    springboot 定时任务
  • SpringBoot实现定时任务的三种方式小结
    目录定时任务实现的三种方式使用Timer使用ScheduledExecutorService使用Spring Task1.简单的定时任务2.多线程执行SpringBoot三种方式实现...
    99+
    2024-04-02
  • SpringBoot中定时任务@Scheduled注解的使用解读
    目录概述注解定义参数说明源码解析使用详解定时任务同步/异步执行fixedRate/fixedDelay区别项目开发中,经常会遇到定时任务的场景,Spring提供了@Scheduled...
    99+
    2024-04-02
  • SpringBoot+SpringBatch+Quartz整合定时批量任务方式
    目录一、引言二、代码具体实现1、pom文件2、application.yaml文件3、Service实现类4、SpringBatch配置类5、Processor,处理每条数据6、封装...
    99+
    2024-04-02
  • SpringBoot中如何定时任务
    SpringBoot中如何定时任务,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。这篇文章将介绍怎么通过spring去做调度任务。构建工程创建一个Springbo...
    99+
    2023-06-19
  • SpringBoot中定时任务@Scheduled的多线程使用详解
    目录一、@Scheduled注解简介二、@Scheduled的多线程机制三、@Scheduled的多线程问题四、@Scheduled加入线程池来处理定时任务五、@Scheduled详...
    99+
    2023-05-17
    SpringBoot定时任务@Scheduled原理 SpringBoot定时任务@Scheduled使用 SpringBoot定时任务@Scheduled
  • SpringBoot配置ShedLock分布式定时任务
    什么是ShedLock ShedLock是一个在分布式环境中使用的定时任务框架,用于解决在分布式环境中的多个实例的相同定时任务在同一时间点重复执行的问题,解决思路是通过对公用的数据...
    99+
    2024-04-02
  • 在springboot项目中使用quartz如何实现一个定时任务
    今天就跟大家聊聊有关在springboot项目中使用quartz如何实现一个定时任务,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。spring支持多种定时任务的实现。我们来介绍下使用...
    99+
    2023-05-31
    springboot art quartz
  • 定时任务如何在Spring Boot中使用
    本篇文章给大家分享的是有关定时任务如何在Spring Boot中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。Spring Boot中配置定时任务import org.sp...
    99+
    2023-05-31
    springboot 定时任务
  • SpringBoot怎么使用Schedule实现定时任务
    本文小编为大家详细介绍“SpringBoot怎么使用Schedule实现定时任务”,内容详细,步骤清晰,细节处理妥当,希望这篇“SpringBoot怎么使用Schedule实现定时任务”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一...
    99+
    2023-07-05
  • SpringBoot实现固定、动态定时任务 | 三种实现方式
    前言: 阅读完本文:🐱‍👓 知晓 SpringBoot 用注解如何实现定时任务明白 SpringBoot 如何实现一个动态定时任务 (与数据库相关联实现)理解 SpringBoot 实现设置时间执行定时任务 ...
    99+
    2023-10-01
    spring boot java mybatis
  • Java -- 定时任务实现方式
    在Java开发中,定时任务是一种十分常见的功能. 定时任务是在约定时间内执行的一段程序 如每天凌晨24点备份同步数据,又或者电商平台 30 分钟后自动取消未支付的订单,每隔一个小时拉取一次数据等都需要使用到定时器 批量处理数据:批量统计上个...
    99+
    2023-09-09
    Java Quartz Scheduled Xxl-Job
  • Java中定时任务的6种实现方式
    目录1、线程等待实现2、JDK自带Timer实现2.1 核心方法2.2使用示例2.2.1指定延迟执行一次 2.2.2固定间隔执行2.2.3固定速率执行2.3 schedule与sch...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作