广告
返回顶部
首页 > 资讯 > 后端开发 > Python >浅谈在springboot中使用定时任务的方式
  • 569
分享到

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

2024-04-02 19:04:59 569人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

SpringBoot定时任务 在springboot环境下有多种方法,这里记录下使用过的其中两种;1、使用注解,2、通过实现接口的方式。 使用注解的方式虽然比较简单,但是如果项目需要

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
@Component
public 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
//@EnableScheduling
public 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中使用定时任务的方式的文章就介绍到这了,更多相关springboot定时任务内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

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

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

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

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

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

下载Word文档
猜你喜欢
  • 浅谈在springboot中使用定时任务的方式
    springboot定时任务 在springboot环境下有多种方法,这里记录下使用过的其中两种;1、使用注解,2、通过实现接口的方式。 使用注解的方式虽然比较简单,但是如果项目需要...
    99+
    2022-11-12
  • 在springboot中使用定时任务的方式
    本篇内容介绍了“在springboot中使用定时任务的方式”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!springboot定时任务在spr...
    99+
    2023-06-20
  • SpringBoot中怎么使用定时任务
    本篇文章为大家展示了SpringBoot中怎么使用定时任务,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1. 线程实现利用线程可以设定休眠时间的方式可以实现简单的定时任务逻辑。  ...
    99+
    2023-06-02
  • SpringBoot实现定时任务的三种方式小结
    目录定时任务实现的三种方式使用Timer使用ScheduledExecutorService使用Spring Task1.简单的定时任务2.多线程执行SpringBoot三种方式实现...
    99+
    2022-11-12
  • springboot实现定时任务的四种方式小结
    目录TimerScheduledExecutor注解@ScheduledQuartz因为某些需求,要在特定的时间执行一些任务,比如定时删除服务器存储的数据缓存,定时获取数据以及定时发...
    99+
    2023-01-13
    springboot 定时任务
  • 如何在SpringBoot中配置ShedLock分布式定时任务
    本篇文章为大家展示了如何在SpringBoot中配置ShedLock分布式定时任务,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。什么是ShedLockShedLock是一个在分布式环境中使用的定时任...
    99+
    2023-06-15
  • 浅谈SpringBoot在使用测试的时候是否需要@RunWith
    我们在使用SpringBoot进行测试的时候一般是需要加两个注解: @SpringBootTest 目的是加载ApplicationContext,启动spring容器。 @RunW...
    99+
    2023-01-15
    SpringBoot @RunWith SpringBoot测试@RunWith
  • SpringBoot中使用@scheduled定时执行任务的坑
    目录解决办法1.将@Scheduled注释的方法内部改成异步执行2.把Scheduled配置成成多线程执行要注意什么坑 不绕弯子了,直接说这个坑是啥: SpringBoot使用@sc...
    99+
    2022-11-13
  • Python使用定时调度任务的方式
    目录1、简单循环 Simple loops2、简单循环但是使用了线程Simple loops but threaded3、定时调度库 Schedule Library4、Python...
    99+
    2022-11-12
  • SpringBoot中定时任务@Scheduled注解的使用解读
    目录概述注解定义参数说明源码解析使用详解定时任务同步/异步执行fixedRate/fixedDelay区别项目开发中,经常会遇到定时任务的场景,Spring提供了@Scheduled...
    99+
    2022-11-13
  • 浅谈go中cgo的几种使用方式
    目录最简单的CGO程序源码方式调用C函数内部机制编译和链接参数编译参数:CFLAGS/CPPFLAGS/CXXFLAGS链接参数:LDFLAGS通过静态库的方式调用C函数通过动态库的...
    99+
    2022-11-13
  • SpringBoot中定时任务@Scheduled的多线程使用详解
    目录一、@Scheduled注解简介二、@Scheduled的多线程机制三、@Scheduled的多线程问题四、@Scheduled加入线程池来处理定时任务五、@Scheduled详...
    99+
    2023-05-17
    SpringBoot定时任务@Scheduled原理 SpringBoot定时任务@Scheduled使用 SpringBoot定时任务@Scheduled
  • 在springboot项目中使用quartz如何实现一个定时任务
    今天就跟大家聊聊有关在springboot项目中使用quartz如何实现一个定时任务,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。spring支持多种定时任务的实现。我们来介绍下使用...
    99+
    2023-05-31
    springboot art quartz
  • 浅析java中常用的定时任务框架-单体
    目录一、阅读收获二、本章源码下载三、Timer+TimerTask四、ScheduledExecutorService五、Spring Task5.1 单线程串行执行-@Schedu...
    99+
    2022-11-12
  • Java中定时任务的6种实现方式
    目录1、线程等待实现2、JDK自带Timer实现2.1 核心方法2.2使用示例2.2.1指定延迟执行一次 2.2.2固定间隔执行2.2.3固定速率执行2.3 schedule与sch...
    99+
    2022-11-12
  • 定时任务如何在Spring Boot中使用
    本篇文章给大家分享的是有关定时任务如何在Spring Boot中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。Spring Boot中配置定时任务import org.sp...
    99+
    2023-05-31
    springboot 定时任务
  • Java中定时任务的实现方式有哪些
    本篇内容主要讲解“Java中定时任务的实现方式有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java中定时任务的实现方式有哪些”吧!1、线程等待实现先从最原始最简单的方式来讲解。可以先创建...
    99+
    2023-06-25
  • 如何在springboot中利用Quartz实现一个定时任务功能
    如何在springboot中利用Quartz实现一个定时任务功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。一、新建一个springboot工程,并添加依赖<depen...
    99+
    2023-05-31
    springboot art quartz
  • 如何在PHP中使用定时任务函数
    PHP是一种非常流行的服务器端编程语言,它可以帮助我们开发高效、动态的Web应用程序。在编写Web应用程序时,我们经常需要执行一些定时任务,比如定期清理数据,自动发送邮件等等。 实现这些定时任务的一种方法是使用PHP的定时任务函数。在本文中...
    99+
    2023-05-19
    函数 PHP 定时任务
  • PHP中使用Redis实现分布式定时任务
    Redis是一种高性能的内存数据库,它具有快速的读写速度、支持一定级别的持久性和丰富的数据类型等优点。Redis常被用于缓存、消息队列、实时排行榜等场景。在开发中,我们有时会需要实现分布式的定时任务,比如:发送邮件、清理临时文件、更新缓存等...
    99+
    2023-05-15
    分布式 PHP redis
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作