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

SpringBoot定时任务@Scheduled的多线程使用 Scheduled是Spring框架中的一个注解,它可以用于配置定时任务,使得方法可以按照规定的时间间隔定时执行。在使用该注解时,我们可以指定任务的执行时间、循环周期、并发数等参数,从而实现定时任务的功能。在Spring Boot中,@Scheduled注解可以直接应用于方法上。通过以上的分析,我们可以了解到:虽然@Scheduled注解能够非常方便地实现定时任务的功能,但是它也存在一些多线程的问题。为此,需要注意到这些问题,并采取相应的措施来避免它们的出现。 阅读详情

1.在定时任务类上加上注解 @EnableScheduling,开启定时任务管理,
使用@PostConstruct 注解,进行初始化操作,并设置多任务线程池:

@Slf4j
@RequiredArgsConstructor
@EnableScheduling
@Component
public class ScheduleExecuteTaskUtil{

	private static final Map<String, Object> SCHEDULED_TASK_MAP = new LinkedHashMap<>();
	private ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;
	
    @PostConstruct
    public void initTaskList() {
        //设定一个长度为10的定时任务线程池
        scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(10);
        //初始化当前任务 启动自动任务
        initScheduledTask();
    }
}

2.在定时任务加上注解 @Scheduled,fixedDelay为固定延迟时间,单位为ms:

@Scheduled(fixedDelay = 5 * 60 * 1000)
    public void scheduledTaskUpdate() {
        log.info("定时执行自动任务");
        initScheduledTask();
    }

3.定时执行线程池任务,每个机台使用一个线程,
scheduleWithFixedDelay(Runnable command,long initialDelay,long period,TimeUnit unit)
第一个command参数是任务实例,
第二个initialDelay参数是初始化延迟时间,
第三个period参数是间隔时间,
第四个unit参数是时间单元

private void initScheduledTask() {
		//遍历各机台添加自动任务进行执行
        List<MachineInfo> machineInfoList = machineInfoMapper.selectList(lqw);
        for (MachineInfo machineInfo : machineInfoList) {
             this.addScheduledTask(machineInfo.getMachineId());
        }
}

private void addScheduledTask(String machineId) {
        if (!SCHEDULED_TASK_MAP.containsKey(machineId)) {
            ScheduledFuture<?> runnableFuture = scheduledThreadPoolExecutor.scheduleWithFixedDelay(() -> {
            	//机台监控任务
                machineMonitorService.executeMonitor(machineId);
            }, 1, 1, TimeUnit.SECONDS);
            SCHEDULED_TASK_MAP.put(machineId, runnableFuture);
        }
}

注意:开启了多线程之后,需要注意可能会出现重复操作,导致数据异常,需要做其他处理。

Win10 + Linux 双系统删除(Linux) 删除Linux所使用的磁盘分区 进入此电脑->计算机->管理->磁盘管理 阅读详情

相关推荐

Wincc7.5SP1 按钮操作记录(二次确认及语音播报)

Wincc 7.5 SP1 按钮操作记录生成(含二次确认及语音播报) 前面一篇文章已经介绍了“语音播报WINCC报警”,本文是之前功能的延伸,记录按钮操作记录并实现播报。 操作记录及语音播报效果 <创建消息文本> 1. 创建消息文本 消息编号100,消息等级“系统无确认”,消息类型“操作员输入消息”,消息文本“循环水泵启动操作”,其他参数默认。 消息编号101,消息等级“系

徐站的春天 1万+

SpringBoot 定时器和多线程(1) -异步实现方式

Schedule创建的定时任务默认单线程的同步执行,虽然可以通过SchedulingConfigurer指定线程的个数,但是当代码运行起来时还是同步执行,同一个调度任务还需要阻塞等待上一次任务执行完成之后才能继续执行下一次任务。不同调度任务也是同一样的,需要阻塞等待上一个调度任务完成之后,才可以继续执行下一个调度任务。所以我们需要开始定时器的多线程异步执行。

myli92的博客 2858

【PB03F 超详细-环境搭建】蓝牙5.2安信可PB-03F-Kit开发板二次开发环境搭建

PB-03是由深圳市安信可科技有限公司开发的蓝牙模块。本博文介绍安信可PB-03F-Kit开发板的基本情况、开发环境搭建,以及以点亮LED为例介绍程序编写和固件烧录的操作流程。 安信可PB-03F-Kit开发板使用的PHY6252这样一款高集成度的低功耗蓝牙系统级芯片(SoC),专为物联网(IoT)、移动设备、可穿戴电子设备、智能家居等各种应用而设计。......

qq_44078824的博客 1万+

SpringBoot中@Scheduled实现多线程并发定时任务

SpringBoot中@Scheduled实现多线程并发定时任务 1.背景 Spring Boot实现定时任务非常容易,只需要使用Spring自带的Schedule注解 @Scheduled(cron = "0 */1 * * * ?") public void cancleOrderTask() { //实现业务 } 记得在启动类中开启定时任务 @EnableScheduling //开启定时任务 定时任务开启成功,但所有的任务都是在同一个线程池中的同一个

山路曲折盘旋,但毕竟朝着顶峰延伸 1万+

点云直线检测-3DLineDetection复现

点云直线分割-Fast 3D line detection

阁楼 8165

密码学新手必看:三大顶级会议论文下载与阅读指南(附完整资源链接)

本文为密码学新手提供了系统性的三大顶级会议(Crypto、Eurocrypt、Asiacrypt)论文学习指南。内容涵盖如何高效获取最新论文资源、结构化精读论文的方法论,以及将理论转化为代码实践的路径,旨在帮助初学者快速构建密码学知识体系并应用于研究。

weixin_29214691的博客 336

@Scheduled定时任务单线程和多线程

@Scheduled; 多线程;线程池

jason_spark的博客 2390

【TestNG自动化测试框架详解】

TestNG是一款设计测试用例执行流程的测试框架。

weixin_43936332的博客 1549

springboot中的任务处理:异步,邮件,定时

1.创建异步处理请求 2.controller调用异步业务请求的方法 3.主程序开启异步处理,创建多线程池! 二.邮件任务 1.导包 2.配置文件properties 3.邮件发送方法 三.定时执行任务 1.写一个需要定时执行的任务 2.主程序开启定时调用 ok!...

weixin_48595687的博客 200

HBM PHY 架构解析:从主控模块到DWORD设计的深度探索

本文深入解析了HBM PHY的完整架构,从作为系统大脑的PUB主控模块出发,详细阐述了其CSR控制、初始化与训练引擎的核心功能。进而剖析了负责命令传输的AWORDX2模块与作为数据高速公路的DWORD模块的设计奥秘,包括其双向数据流、精密时钟对齐与延迟线校准机制。最后,探讨了顶层MASTER PHY的整合作用及从DFI到DRAM的完整数据通路,为理解这一高性能内存接口的关键物理层设计提供了全面视角。

weixin_29306011的博客 306

SpringBoot创建定时任务的三种方法:基于注解(@Scheduled) 基于接口(SchedulingConfigurer) 基于注解设定多线程定时任务

SpringBoot创建定时任务有三种方式: 基于注解(@Scheduled) 基于接口(SchedulingConfigurer) 基于注解设定多线程定时任务 此任务使用了Springboot基于注解(@Scheduled)的调度器,所以我们将重点讲解基于注解(@Scheduled)的调度器,其他调度器可以参照,比对学习。 @Scheduled注解默认是串行的,单线程,当开启多个任务时,任务的执行时间会受上一个任务执行时间的影响 @Configuration @EnableScheduling

weixin_41147129的博客 1735

android 14.0 控制wifi启用禁用功能实现

在14.0的产品rom定制化开发中,在产品开发中,对于功能的开发的功能也是挺多的,而在对于wifi的功能定制需求,有要求需要通过系统属性来控制wifi开关是否可以打开 来控制是否可以连接wifi,打开控制wifi的功能,接下来分析wifi的开启流程来实现该功能的实现

安卓兼职framework和app工程师的博客 1775

玩转SpringBoot之定时任务详解(讲的很好)

序言 使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式: 一、基于注解(@Scheduled) 二、基于接口(SchedulingConfigurer) 前者相信大家都很熟悉,但是实际使用中我们往往想从数据库中读取指定时间来动态执行定时任务,这时候基于接口的定时任务就派上用场了。 三、基于注解设定多线程定时任务 静态:基于注解 基于注解@Scheduled默认为单...

1万+

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

springboot使用@Scheduled定时任务详解

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

qq_20667023的博客 1294

深度学习工具包 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-15】异步、邮件、定时任务 ## 异步任务

异步任务 创建一个service包 创建一个类AsyncService 异步处理还是非常常用的,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。 编写方法,假装正在处理数据,使用线程设置一些延时,模拟同步等待的情况; @Service public class AsyncService { public void hello(){ try { Thread.s

alovelypeach的博客 388

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

java定时器阻塞主线程_Springboot集成定时器和多线程异步处理操作

需求:用@schedule标签进行定时处理逻辑,由于业务处理速度慢,需要每次执行逻辑放在不同的线程里异步执行springboot集成多线程异步,直接上配置:/*** 线程池异步配置*/@Configuration@EnableAsyncpublic class ThreadExecutorConfigimplements AsyncConfigurer {@Overridepublic Execu...

weixin_36454202的博客 644

一篇简单的文章带你玩转SpringBoot 之定时任务详解

使用5W,如果5日是星期六,则将在最近的工作日:星期五,即4日触发。如果5日是星期天,则在6日触发;例如想在每月的20日触发调度,不管20日到底是星期几,则只能使用如下写法: 13 13 15 20 *?数据库准备好数据之后,我们编写定时任务,注意这里添加的是TriggerTask,目的是循环读取我们在数据库设置好的执行周期,以及执行相关定时任务的内容。:表示起始时间开始触发,然后每隔固定时间触发一次,例如在Minutes域使用5/20,则意味着5分钟触发一次,而25,45等分别触发一次。

林夕 1198

SpringBoot定时任务及Cron表达式详解

0.SpringBoot定时任务及Cron表达式详解 2017年12月25日 14:01:02 fujiawei3710 阅读数:2364更多 个人分类: springBoot从零开始 一、定时任务概述 后台项目开发中经常会用到定时任务,现在实现定时任务都方式也是多种多样。下面列举几种常见的定时任务实现方式: 1.Quartz:Quartz的使用相当广泛,它是一个功能...

f45056231p的博客 570

13-SpringBoot-异步任务-邮件任务-定时任务

1、异步任务 1、创建一个service包 2、创建一个类AsyncService 异步处理还是非常常用的,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。 编写方法,假装正在处理数据,使用线程设置一些延时,模拟同步等待的情况; @Service public class AsyncService { public void hello(){ try{ Thre

qq_45632660的博客 329

Spring Boot-定时任务

目录 1.创建任务类 2.开启定时任务 3.执行时间的配置 4.多线程处理定时任务 1.创建任务类 @Component public class SchedulerTask1 { private Log log= LogFactory.getLog(SchedulerTask1.class); @Scheduled(cron = "0/5 * * * * *")...

u010277958的博客 412

SpringBoot中的异步、定时、邮件

异步任务 1、创建一个service包 2、创建一个类AsyncService 异步处理还是非常常用的,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。 编写方法,假装正在处理数据,使用线程设置一些延时,模拟同步等待的情况; @Service public class AsyncService { public void hello(){ try { Thre

恒88888888的博客 210

Spring Boot 定时任务单线程和多线程

Spring Boot 的定时任务: 第一种:把参数配置到.properties文件中: 代码: package com.accord.task; import java.text.SimpleDateFormat;import java.util.Date; import org.springframework.scheduling.annotati...

WGH100817的博客 199

SpringBoot(11) - - SpringBoot定时调度

123

Strugglein的博客 377

SpringBoot中实现简单类型定时任务

在SpringBoot项目中实现简单类型的定时任务。

成长记录——编程、跑步、阅读、未来…… 1851

Springboot整合Schedule实现定时任务

目录 前言 一、定时任务的有哪些实现方式 二、Springboot整合Schedule实现定时任务 使用@Scheduled注解创建定时任务 代码样例 开启定时任务 总结 前言 有时候在开发中经常会使用一些定时的任务,比如果整点推送,或者是每隔一段时间给客户发送一个消息等等。 定时任务一般会存在 中大型企业级 项目中,为了减少 服务器、数据库 的压力,往往会以 定时任务 的方式去完成某些业务逻辑。 常见的就是 金融服务系统推送回调,一般支付系统订单在没有收到成功的回调返回内容时会 持续性的

hzjlltj的专栏 677
上一篇: 多线程处理共享文件夹中的excel文件数据
下一篇: SpringBoot使用@Async注解,实现异步任务
Java-xy²
博客等级 码龄10年 33粉丝 47原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值