java实现任务调度

java常见的三种定时任务调度框架介绍 阅读详情

最近的一个小项目是做一个简单的数据仓库,需要将其他数据库的数据抽取出来,并通过而出抽取成页面需要的数据,以空间换时间的方式,让后端报表查询更快。
因为在抽取的过程中,有一定的先后顺序,需要做一个任务调度器,某一优先级的会先执行,然后会进入下一个优先级的队列任务中。
先定义了一个Map的集合,key是优先级,value是任务的集合,某一个优先级内的任务是并发执行的,而不同优先级是串行执行的,前一个优先级执行完之后,后面的才会执行。

ConcurrentHashMap<Integer/* 优先级. */, List<BaseTask>/* 任务集合. */> tasks = new ConcurrentHashMap<>();

这个调度管理有一个演进的过程,我先说第一个,这个是比较好理解的。
第一个版本:
首先对tasks集合中的key进行一个排序,我定义的是数字越小就有限执行,则进行遍历key值,并取出某个优先级的任务队列,执行任务队列的任务。任务的执行交给线程池去执行,在遍历内部,需要不断的检查这个队列中的任务是否都执行了,没有则一直等待否则进入到下个队列,任务执行的时候可能会抛出异常,但是不管任务是否异常,都将任务状态设置已执行。
下面是其核心代码:

public void run() {
    //对key值进行排序
    Enumeration<Integer> keys = tasks.keys();
    List<Integer> prioritys = new ArrayList<>();
    while (keys.hasMoreElements()) {
      prioritys.add(keys.nextElement());
    }
    Collections.sort(prioritys);//升序
    //对key进行遍历,执行某个某个优先级的任务队列
    for (Integer priority : prioritys) {
      List<BaseTask> taskList = tasks.get(priority);
      if (taskList.isEmpty()) {
        continue;
      }
      logger.info("execute priority {} task ", taskList.get(0).priority);
      for (BaseTask task : taskList) {
        executor.execute(() -> {
          try {
            task.doTask();
          } catch (Exception e) {
            e.printStackTrace();
          }
        });//线程中执行任务
      }
      while (true) {//等待所有线程都执行完成之后执行下一个任务队列
        boolean finish = true;
        for (BaseTask t : taskList) {
          if (!t.finish) {
            finish = false;
          }
        }
        if (finish) {//当前任务都执行完毕
          break;
        }
        Misc.sleep(1000);//Thread.sleep(1000)
      }
      Misc.sleep(1000);
    }
  }

关键代码很好理解,在任务执行之前,需要对所有任务都初始化,初始化的时候给出每个任务的优先级和任务名称,任务抽象类如下:

public abstract class BaseTask {
  public String taskName;//任务名称
  public Integer priority; //优先级
  public boolean finish; //任务完成?
  /**
   * 执行的任务
   */
  public abstract void doTask(Date date) throws Exception;

第一个版本的思路很简单。
第二个版本稍微有一点点复杂。这里主要介绍该版本的内容,后续将代码的链接附上。
程序是由SpringBoot搭建起来的,定时器是Spring内置的轻量级的Quartz,使用Aop方式拦截异常,使用注解的方式在任务初始化时设置任务的初始变量。使用EventBus解耦程序,其中程序简单实现邮件发送功能(该功能还需要自己配置参数),以上这些至少需要简单的

任务调度问题(贪心算法) Java实现 这个问题是《算法导论》上的一个经典的贪心算法问题——单处理器上具有期限和惩罚的单位时间任务调度问题,目标是使惩罚最小。 问题描述: 具有截止时间和误时惩罚的单位时间任务时间表问题可描述如下: (1) n 个单位时间任务的集合S={1,2,…,n}(n≤500); (2) 任务i的截止时间deadline[i],1≤d[i]≤n,即要求任务i在时间d[i]之前结束; (3) 任务i 的误时惩罚1≤weught[i]<1000,即任务i 未在时间d[i]之前结束将招致w[i]的惩罚;若按时完成则无惩罚 阅读详情

相关推荐

Java实现任务调度

任务调度是计算机程序中常见的一种需求,可以用来定期执行特定的任务或在特定的时间点执行任务。在Java中,我们可以使用多种方式来实现任务调度,包括使用Java标准库提供的定时任务类、使用第三方库如Quartz等。这是使用Java实现任务调度的两种常见方法。Quartz是一个功能强大且灵活的任务调度框架,可以用于在Java应用程序中实现复杂的任务调度需求。首先,我们需要创建一个继承自TimerTask的任务类,该类包含要执行的任务代码。接下来,我们需要创建一个实现Job接口的任务类,该类包含要执行的任务代码。

UtdPatch的博客 272

使用 Java 实现一个简单且高效的任务调度框架

本文系统地介绍了如何使用 Java 设计与实现一个高吞吐、高可用、轻量级的任务调度框架。内容涵盖任务状态管理、线程池并发执行、阻塞队列解耦、失败重试机制及分布式扩展方案(如分片与 Redis 中心化调度)。通过逐步深入的架构演进与代码示例,帮助读者理解调度系统的核心设计原则与工程实现,为构建可扩展的任务处理平台提供实用参考。

曾经“等你生日那天”都遥远得像未来,如今却可欢愉的挥手说“下个十年见” 14万+

基于java的任务调度系统设计与实现

任务调度系统是计算机系统中非常重要的一个组件,它能够有效地管理计算机系统的资源,使得多个任务能够按照一定的优先级进行调度。在基于Java的任务调度系统中,任务调度是核心的一部分,它涉及到多个线程的同步和交互,以及多个任务之间的调度。本文将总结基于Java的任务调度系统设计与实现的系统性能评估的总结和分析。首先,任务调度系统的性能评估需要考虑到多个任务之间的调度,以及多个线程之间的交互。在基于Java的任务调度系统中,任务调度涉及到多个线程之间的同步和交互,以及多个任务之间的调度。

biyesheji1000的专栏 1381

V93000与SmarTest 8:SoC测试开发实战指南

半导体测试是芯片量产中不可或缺的一环,ATE(自动测试设备)作为核心工具,决定了芯片良率与测试成本。随着SoC芯片集成度不断攀升,多引脚、高性能、多Site并行测试成为行业刚需,而这背后离不开一套稳定高效的测试开发环境。V93000(业内常称V93K)作为主流SoC测试平台,以其模块化架构和强大的并行能力成为众多产线的首选;其配套的SmarTest 8软件,则通过Perl脚本化的编程方式,将测试流程拆解为可复用的Test Method与Test Suite,帮助工程师灵活构建从开短路测试到功能验证的完整测试

weixin_26850069的博客 374

Mann-Kendall检验全解析:从原理到11种变体及Python实现

本文全面解析Mann-Kendall检验,从基础原理到应对自相关、季节性等复杂数据的11种关键变体,如Hamed-Rao修正、季节性MK和趋势自由预白化(TFPW)。详细阐述各方法的适用场景与数学原理,并提供完整的Python实战代码,帮助研究者针对不同数据特性选择最稳健的趋势分析方法。

weixin_29050271的博客 471

FPGA 学习系列(2):Verilog 语法基础

Verilog 由门级建模数据流建模行为建模门级建模(Gate Level Modeling):使用基本逻辑门描述电路,接近硬件物理结构。数据流建模(Data Flow Modeling):使用assign语句进行组合逻辑建模,类似数学方程式。行为建模(Behavioral Modeling):使用always代码块和if-elsecase等控制语句建模,抽象程度较高。Verilog 代码一般由模块(module)组成,每个模块描述一个独立的硬件功能。

Azperk的博客 997

WRF所需气象数据的下载方法

#数据下载是个大问题,巧妇难为无米之炊,没有数据就无法模拟啦,疫情期间国外服务器响应慢,打开网页慢都很正常啦~ WRF数据所需要的外部数据分为两种:静态地理数据,grib格式的气象数据(NAM、GFS、RUC、AGRMET等)。静态地理数据可以从WRF官网获得,比较简单,这里不做介绍。所以这篇日志重点介绍的是气象数据的获取。 提前说明,WRF官网不提供气象数据,但WRF官网提供各类气象数据的下载网址链接,所以我们下载一般还是从WRF官网开始。首先进入WRF官网,然后点击WRF ARW Uusres’ .

六出的博客 1万+

国家大地2000坐标系投影坐标转高德地图经纬度坐标-【高斯投影坐标】

国家大地2000坐标系投影坐标转换成高德经纬度坐标显示画图。

devil_zhuzhu的博客 1万+

《Hadoop大数据技术原理与应用》(第2版)黑马程序员的课后习题答案

《Hadoop大数据技术原理与应用》(第2版)黑马程序员的课后习题答案

qq_36773158的博客 4668

OmniDrive(3):逐行代码详解

模型效果: 端到端联合规划与推理 接下来,简单介绍下训练的配置 1.1 模型配置 模型基于sparse query based的3D Bev感知框架StreamPetr ,用query来编码动态目标(如车辆、行人)和静态地图元素(如车道线)。(1) tran、test和val数据配置 指定真值的文件路径: ann_file 指定输出处理的pipeline: 训练使用, test 和val使用 指定是否需要时序训练seq_mode (2)数据处理pipeline 自定义的Dataset 通过类实现,训

@bangbang的博客 726

铁路场景雷达点云目标识别与追踪系统

本文介绍了一种基于毫米波雷达的铁路货运车站安全监控系统。该系统采用分布式架构,通过多个毫米波雷达节点采集点云数据,经过坐标转换、多雷达融合等处理后,利用机器学习算法实现列车、行人等目标的实时识别与追踪。系统包含数据采集层、处理层、目标识别层、追踪层、预警决策层和可视化层,能够克服传统视频监控受环境影响大的缺点,实现全天候可靠监测。文中详细展示了雷达数据解析和点云预处理的代码实现,包括坐标转换、数据格式解析和体素网格滤波等关键技术。该系统可有效预警铁路场景下的碰撞风险,提升货运车站的安全管理水平。

huanghm88的专栏 129

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

深度学习工具包 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")

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

上一篇: java里面如何提升编写速度
下一篇: 学会使用Java8新特性
core_ice
博客等级 码龄12年 7粉丝 30原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值