SpringBoot - 如何使用@Scheduled处理定时任务?

SpringBoot的@Scheduled和@Schedules有什么区别 对于更复杂的需求,比如调整线程池大小或者设置线程名称前缀等,你可以通过自定义来进行配置。Spring提供了几种内置的调度器实现,如和。@Override@Override@Override// 自定义异常处理逻辑。 阅读详情

写在前面

定时任务是项目开发中最常见的功能之一,如定时统计订单数、定时进行数据库备份、定时发送邮件以及周期性调度等。简单的定时任务可以直接通过 Spring 的 @Scheduled 注解实现,复杂的定时任务则可以通过集成 Quartz 来实现。
(1)@Scheduled只能针对本机的任务进行调度,当应用为了增加发负载量,都是使用多机部署时,就会出现问题:在每一台机器上都会同时执行定时调度任务,产生很多重复/垃圾数据。所以在使用@Scheduled进行任务调度时,一定要配合REDIS的分布式锁,让定时调度任务只在一台机器上执行。
(2)所有的定时任务都是由同一个线程池的同一个线程来完成的,如果有多个定时任务,其中一个任务执行时间过长,则有可能会导致其他后续任务被阻塞直到该任务执行完成。如何解决呢?

如何使用@Scheduled?

1. 开启定时任务

在项目启动类上添加 @EnableScheduling 注解开启定时任务。

2. 设置定时任务
@Component
public class MySchedule {
    // fixedDelay, 表示上次调用结束后与下次调用之间的固定时间,单位是毫秒
    // 表示距离上次调用后1秒再执行
    @Scheduled(fixedDelay = 1000)
    public void fixedDelay() {
        System.out.println("fixedDelay:" + new Date());
    }
 
    // fixedRate, 表示多久执行一次,单位是毫秒,与cron的/通配符用法相似
    // 表示每2秒执行一次 
    @Scheduled(fixedRate = 2000)
    public void fixedRate() {
        System.out.println("fixedRate:" + new Date());
    }
 
    // initialDelay, 表示第一次延迟多少毫秒执行,单位是毫秒
    // 表示每2秒执行一次, 第一次执行时, 延迟2秒执行
    @Scheduled(initialDelay = 1000, fixedRate = 2000)
    public void initialDelay() {
        System.out.println("initialDelay:" + new Date());
    }
 
    // 使用cron 表达式(每分钟执行一次)
    @Scheduled(cron = "0 * * * * ?")
    public void cron() {
        System.out.println("cron:" + new Date());
    }
}

注意事项

(1)SPRING的@Scheduled注解需要标注在实现方法上;
(2)被@Scheduled标注的方法不能有返回值;
(3)如果被@Scheduled标注的方法需要与应用程序上下文的其他对象进行交互,通常是通过依赖注入的方式来实现;
(4)被@Scheduled标注的方法的类上要有组件的注解@Component;(当然也可以使用 @Controller 和 @Service 等其他与 @Component 作用相同的注解)
(5)所有的定时务在同一个线程中。

源码、示例及DEMO

源码、示例及DEMO

MIT IDSS深度解析:跨学科融合与系统科学实践 麻省理工学院的IDSS(Institute for Data, Systems, and Society, IDSS)是一个致力于通过先进分析方法推动教育与研究的前沿机构。它将工程学、信息科学和数据科学的方法与社会科学的分析方法相结合,以应对复杂的社会挑战。 阅读详情

相关推荐

Python地理空间数据库之geopandas使用详解

地理空间数据分析在许多领域中都有着广泛的应用,包括地理信息系统(GIS)、城市规划、环境科学、地质勘探等。Python GeoPandas是一个强大的库,旨在简化地理空间数据的处理和分析。本文将深入介绍GeoPandas库,包括其基本概念、功能特性、示例代码以及在实际应用中的应用场景。

Rocky006的博客 1万+

SpringBoot中的定时任务@Scheduled的使用详情及可能出现的坑

https://blog.csdn.net/qq_29550537/article/details/91974893

无术不学的博客 293

机场数据治理系列介绍(1):机场行业数据中台中的数据管理顶层设计方案

民航机场行业的数据中台中,有关数据管理顶层设计方案需要结合机场行业的业务特点和技术需求进行具体的设计,今日我们简要考量设计提供一个参考方案:

机场信息系统研究员的专栏 1614

定时处理事务(Spring Task)

*** 自定义定时任务类*/@Component@Slf4j/*** 定时任务 每隔5秒触发一次*/")log.info("定时任务开始执行:{}",new Date());

baiwangyou的博客 758

手把手教你用Arduino和开源电路DIY一个手机连接的电化学传感器(附GitHub源码)

本文详细介绍了如何利用Arduino和开源电路DIY一个手机连接的电化学传感器,成本不到300元即可复现价值数千元的专业设备。从硬件选型、电路搭建到固件开发和手机应用实现,手把手教你完成整个项目,特别适合科研人员、环境监测爱好者和理工科学生。附GitHub源码,方便快速上手和扩展功能。

weixin_42561040的博客 341

mipi协议中的calibration和scramble模式

在MIPI(Mobile Industry Processor Interface)协议中,calibration(校准)和scramble(加扰)模式是两个重要的特性,它们分别用于优化数据传输的准确性和减少信号干扰。

flomingo1的专栏 2409

定时任务——@Scheduled注解做定时任务

在启动类上面加上 @EnableScheduling 注解 开启 定时任务 import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.ann...

qq_41505160的博客 7587

python调用hypermesh调用tcl_TclTk如何调用HyperMesh运行tcl脚本文件

#Tcl/Tk编写界面部分set t [toplevel .tp]focus $tgrab $tset Filename "E:/CAE_Tech/process_files/88/Example.tcl"set Font "Times 12 bold"wm title $t "Call HyperMesh"wm attribute $t -topmost 1wm withdraw $tset t...

weixin_39541681的博客 1603

spring调度注解@Scheduled(含分布式)

本文主要介绍spring调度注解@Scheduled,以及分布式场景的改造思路。

sjzwangxufeng的专栏 6755

语音信号的AGC自适应增益调整matlab仿真

语音信号的自动增益控制(Automatic Gain Control,AGC)是音频处理领域中的一项重要技术。其核心功能是实时调整输入信号的幅度,使其保持在一定范围内,以优化输出信号的质量。AGC广泛应用于语音通信、语音识别、音频录制和播放等领域,旨在解决输入信号幅度波动问题,确保输出信号的稳定性和清晰度。一、AGC的基本原理1.1 幅度调整自动增益控制的基本原理是根据输入信号的幅度动态地调整系统的增益。

平时工作较为繁忙,私信消息一般晚上回复,谢谢大家~~ 929

在 PFCG 中完成 SAP Fiori 对象分配:把 Business Catalog、Space、Page 与授权一次讲透

摘要:SAP Fiori权限配置的关键在于理解Business Catalog与Space的分层授权逻辑。传统SAP GUI中直接分配事务码的方式不适用于Fiori环境,必须通过PFCG为角色分配Catalog(提供应用访问权限)和Space(控制首页展示结构)。Catalog会自动解析所需OData服务授权,而Space则决定用户在Launchpad中看到的导航布局。常见错误包括直接分配Page而非其所属Space,或仅配置Space而忽略Catalog。最佳实践是优先使用Catalog驱动授权提议,再在

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 331

SpringBoot使用@Scheduled注解,实现多线程定时任务处理

1.在定时任务类上加上注解 @EnableScheduling,开启定时任务管理,注意:开启了多线程之后,需要注意可能会出现重复操作,导致数据异常,需要做其他处理。第二个initialDelay参数是初始化延迟时间,3.定时执行线程池任务,每个机台使用一个线程,第一个command参数是任务实例,第三个period参数是间隔时间,第四个unit参数是时间单元。

csdnxyy的博客 708

零基础学习CANoe Panel(17)—— Panel CAPL Function

CANoe内置了几个CAPLFunction,允许我们在CAPL运行时动态的更改Panel控件的属性,比如打开某个panel,禁用某个控件,更改控件颜色等。

蚂蚁小兵 3530

SpringBoot(十七)——————异步任务、定时任务、邮件任务

异步任务 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。 两个注解: @EnableAysnc:开启异步处理 @EnableAsync @SpringBootApplication pu...

不积跬步无以至千里 523

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

springboot 与 任务(异步任务,邮件任务,定时任务)

springboot 与 任务 一、异步任务 @EnableAsync + @Async // 开启异步任务注解功能 @EnableAsync 标识在启动类上面 @Async 标识在方法上面,标识异步方法 二、定时任务 定时任务: 项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。 Spring为我们提供了异步...

itboy 478

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

狂神说:Springboot学习笔记(十三)——异步、定时、邮件任务

狂神说原文链接 bilibili视频地址 文章目录 前言 一、异步任务 二、定时任务 三、邮件任务 前言 在我们的工作中,常常会用到异步处理任务,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。还有一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息。还有就是邮件的发送,微信的前身也是邮件服务呢?这些东西都是怎么实现的呢?其实SpringBoot都给我们提供了对应的支持,我们上..

LeeBlog 870

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

SpringBoot【注解 01】@Scheduled实现定时任务的串行和并行执行

SpringBoot @Scheduled 实现定时任务的串行和并行执行

Java与大数据相关实践内容分享! 3172

springboot中@Scheduled定时任务的线程修改

@Scheduled简介: springboot中自带的@Scheduled注解,以将它看成一个轻量级的Quartz,默认情况下是单线程的。也就是无论同时有多少个任务需要执行,都需要排队等待某个任务完成之后才能继续下一个任务。 我们可以通过xml配置任务线程池,也可以通过继承SchedulingConfigurer类并重写方法,这里主要将继承方Scheduling...

sayoko06的博客 2339

springboot的异步任务、定时任务的简单案例

异步任务简单案例 在我们开发项目时,常常会用到异步处理任务,比如我们在网站上发送邮件,后台会去发送邮件,此时会造成前台响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。 1. 新建一个service包 2. 创建AsyncService类 @Service public class AsyncService { public void hello(){ try { Thread.sleep(3000);

L_GRAND_ORDER的博客 2143

SpringBoot学习-part67整合三类任务

异步任务 开启异步模式 @EnableAsync //开启异步注解功能 @SpringBootApplication public class Springboot04TaskApplication { public static void main(String[] args) { SpringApplication.run(Springboot04TaskApplication.class, args); } } 2)异步服务 @Service public cla

Ezerbel的博客 182

springboot使用@Scheduled定时任务详解

使用@Scheduled注解 springboot使用定时任务非常方便,只需要在方法上增加@Scheduled注解即可,同时需要使用@EnableScheduling开启定时任务 1.springboot 启动类添加 @EnableScheduling 注解 import org.springframework.boot.SpringApplication; import org.springfr...

qq_20667023的博客 1293

SpringBoot:异步 定时 邮件任务

异步 定时 邮件

yooppa的博客 203

@scheduled cron启动后和每小时执行_Spring Boot 使用 @Scheduled 注解创建定时任务

在项目开发中我们经常需要一些定时任务来处理一些特殊的任务,比如定时检查订单的状态、定时同步数据等等。在 Spring Boot 中使用 @Scheduled 注解创建定时任务非常简单,只需要两步操作就可以创建一个定时任务:1、在定时任务类上增加 @EnableScheduling 注解2、在要执行任务的方法上增加 @Scheduled 注解下面是我使用 cron 表达式创建一个简单的定时任务:im...

weixin_42476888的博客 1万+

Spring使用@Scheduled注解实现定时任务

文章目录定义详细说明fixedDelayfixedRatecron特殊字符 Spring项目中,通过在方法上添加注解@Scheduled来实现定时任务 定义 先看下@Scheduled注解的定义,很清楚的看到,实现定时任务有多种选择,如cron, fixedDelay … 等等 package org.springframework.scheduling.annotation; import java.lang.annotation.Documented; import java.lang.annotat

拾年一剑 的专栏 1023
上一篇: CENTOS下的CRON服务及CRONTAB命令的区别
下一篇: SpringBoot - 集成Quartz框架之CRON表达式
cloneme01
博客等级 码龄20年 2万+粉丝 248原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cloneme01

谢谢您的支持与鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址