之前一篇用过了如何在使用创建最简单的任务:比如每天定时清空系统的缓存

这篇文章主要讲解:如何运用elastic-job-lite做灵活的细粒度任务,比如:

如何定时取消某个订单在下订单后30分钟未支付的订单,并改变订单状态?

如何让某个用户在获得7天体验会员在七天后改变这个会员的会员状态?

某个用户想定时发布一篇文章?

如何给某个会员在生日当天发送一条祝福短信?

elastic-job-lite 就能实现这样的需求……

主要是任务配置,任务执行类都是一样的,下面贴出了demo,仅限于单应用节点时,主要为了实现如何动态的配置任务参数并达到上述需求,方法应用比较简单

首先要有任务(作业)类,并交给spring管理类

/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/ package com.dianji.task_server.job.exec; import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import java.text.MessageFormat; @Slf4j
@Component
public class OrderExpireJob implements SimpleJob {
@Value("${serverFlag}")
private String serverFlag; @Override
public void execute(final ShardingContext shardingContext) {
int shardingItem = shardingContext.getShardingItem();
String jobName = shardingContext.getJobName();
String jobParameter = shardingContext.getJobParameter();
String logRule = "「执行订单超时任务」任务名:{0},订单号:{1},任务分片索引:{2},服务进程「{3}」";
String logStr = MessageFormat.format(logRule, jobName, jobParameter, shardingItem, serverFlag);
log.info(logStr);
}
}

任务了demo代码

接着就是任务(作业)配置了

package com.dianji.task_server.job.config;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.event.JobEventConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.dianji.task_server.job.exec.OrderExpireJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; /**
* 动态添加任务配置
*
* @author szliugx@gmail.com
* @create 2018-10-25 下午5:16
**/
@Slf4j
@Component
public class DynamicAddJobConfig {
@Autowired
private ZookeeperRegistryCenter regCenter; @Autowired
private JobEventConfiguration jobEventConfiguration; public void dynamicAddSimpleJobScheduler(SimpleJob simpleJob, String jobName, String jobParameter, String cron,
int shardingTotalCount, String shardingItemParameters) {
new SpringJobScheduler(
simpleJob,
regCenter,
getLiteJobConfiguration(
jobName,
jobParameter,
OrderExpireJob.class,
cron,
shardingTotalCount,
shardingItemParameters),
jobEventConfiguration).init();
} /**
* 任务配置
*
* @param jobName
* @param jobParameter
* @param jobClass
* @param cron
* @param shardingTotalCount
* @param shardingItemParameters
* @return
*/
private LiteJobConfiguration getLiteJobConfiguration(
final String jobName,
final String jobParameter,
final Class<? extends SimpleJob> jobClass,
final String cron,
final int shardingTotalCount,
final String shardingItemParameters) {
return LiteJobConfiguration.newBuilder(
new SimpleJobConfiguration(
JobCoreConfiguration.newBuilder(
jobName,
cron,
shardingTotalCount
).shardingItemParameters(shardingItemParameters).jobParameter(jobParameter).build(),
jobClass.getCanonicalName()
)
).overwrite(true).build();
}
}

作业配置代码

最后,主动触发任务添加,这里用了一个restful API 的URL来请求 测试 「让某个订单1分钟后执行过期作业」  任务添加

package com.dianji.task_server.web.controller;

import com.dianji.task_server.job.config.DynamicAddJobConfig;
import com.dianji.task_server.job.exec.OrderExpireJob;
import com.dianji.task_server.util.ResultUtils;
import com.dianji.task_server.web.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date; /**
* 测试控制器
*
* @author szliugx@gmail.com
* @create 2018-10-17 上午9:46
**/
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {
@Autowired
DynamicAddJobConfig dynamicAddJobConfig; @Autowired
private OrderExpireJob orderExpireJob; @GetMapping("/addTask")
public Result addTask(HttpServletRequest request) {
Date date = new Date(); // 当前时间
String orderNo = String.valueOf(date.hashCode()); // 订单号
String jobName = "OrderExpireJob-" + orderNo; // 任务名称(不能重复,不然容易覆盖掉)
Date expireTime = addMin(date, 1); // 测试时,1分钟即可
String cron = testGetCron(expireTime); // 得到cron表达式
String jobParameter = orderNo; // 将订单号作为参数
int shardingTotalCount = 1; // 分片总数
String shardingItemParameters = "0=a"; // 分片参数
dynamicAddJobConfig.dynamicAddSimpleJobScheduler(orderExpireJob, jobName, jobParameter, cron,
shardingTotalCount, shardingItemParameters);
log.info("「添加订单超时任务」,任务名{},订单号{}", jobName, jobParameter);
return ResultUtils.success();
} /**
* 仅测试使用方法,日期转cron表达式
*
* @param date 待处理日期
* @return
*/
private String testGetCron(java.util.Date date) {
String dateFormat = "ss mm HH dd MM ? yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
String formatTimeStr = "";
if (date != null) {
formatTimeStr = sdf.format(date);
}
return formatTimeStr;
} /**
* 仅测试使用方法,给指定的日期添加分钟
*
* @param oldDate 需要处理日期
* @param number 添加的分钟数
* @return
*/
private Date addMin(Date oldDate, int number) { Calendar c = Calendar.getInstance();
c.setTime(oldDate);
c.add(Calendar.MINUTE, number);// 添加分钟 return c.getTime();
}
}

测试添加代码

应用跑起来后,访问 /test/addTask 查看日志结果:

作业维护后台,能看见执行的这些 订单过期任务

elastic-job 分布式定时任务框架 在 SpringBoot 中如何使用(二)动态添加任务需求的更多相关文章

  1. elastic-job 分布式定时任务框架 在 SpringBoot 中如何使用(一)初始化任务并定时执行

    第一篇需要实现一个最简单的需求:某个任务定时执行,多台机子只让其中一台机子执行任务 一.安装 分布式应用程序协调服务 zookeeper,安装步骤在链接里面 Linux(Centos7)下安装 zoo ...

  2. 分布式定时任务框架——python定时任务框架APScheduler扩展

    http://bbs.7boo.org/forum.php?mod=viewthread&tid=14546 如果将定时任务部署在一台服务器上,那么这个定时任务就是整个系统的单点,这台服务器出 ...

  3. Elastic-Job - 分布式定时任务框架

    Elastic-Job - 分布式定时任务框架 摘要 Elastic-Job是ddframe中dd-job的作业模块中分离出来的分布式弹性作业框架.去掉了和dd-job中的监控和ddframe接入规范 ...

  4. 分布式定时任务框架比较,spring batch, tbschedule jobserver

    分布式定时任务框架比较,spring batch, tbschedule jobserver | 移动开发参考书 分布式定时任务框架比较,spring batch, tbschedule jobser ...

  5. 基于spring+quartz的分布式定时任务框架

    问题背景 我公司是一个快速发展的创业公司,目前有200人,主要业务是旅游和酒店相关的,应用迭代更新周期比较快,因此,开发人员花费了更多的时间去更=跟上迭代的步伐,而缺乏了对整个系统的把控 没有集群之前 ...

  6. 在Spring-boot中,为@Value注解添加从数据库读取properties支持

    一般我们会把常用的属性放在工程的classpath文件夹中,以property,yaml或json的格式进行文件存储,便于Spring-boot在初始化时获取. @Value则是Spring一个非常有 ...

  7. Elastic-Job——分布式定时任务框架

    摘要: Elastic-Job是ddframe中dd-job的作业模块中分离出来的分布式弹性作业框架.去掉了和dd-job中的监控和ddframe接入规范部分.该项目基于成熟的开源产品Quartz和Z ...

  8. Quartz小记(一):Elastic-Job - 分布式定时任务框架

    Elastic-Job是ddframe中dd-job的作业模块中分离出来的分布式弹性作业框架.去掉了和dd-job中的监控和ddframe接入规范部分.该项目基于成熟的开源产品Quartz和Zooke ...

  9. Scheduled定时任务器在Springboot中的使用

    Scheduled定时任务器是Spring3.0以后自带的一个定时任务器. 使用方式: 1.添加依赖 <!-- 添加 Scheduled 坐标 --> <dependency> ...

随机推荐

  1. 自定义Spark Partitioner提升es-hadoop Bulk效率

    http://www.jianshu.com/p/cccc56e39429/comments/2022782 和 https://github.com/elastic/elasticsearch-ha ...

  2. [转载]Java集成PageOffice在线打开编辑word文件 - Spring Boot

    开发环境:JDK1.8.Eclipse.Sping Boot + Thymeleaf框架. 一. 构建Sping Boot + Thymeleaf框架的项目(不再详述): 1. 新建一个maven p ...

  3. Awk 从入门到放弃(4) — Aws 格式化

    转:http://www.zsythink.net/archives/1421 print & printf的区别:printf不带\r\n 在awk当中,格式替换符的数量必须与传入的参数的数 ...

  4. html和css命名标准以及常用的框架,我使用的是网易nec

    前端的工作很细,涉及的东西也很多,静态页面和js开发,调接口之类,有时还要自己设计.现在css管理使用less和sass,新东西起码要支持下,具体用与不用看公司的业务需求.前端人员之间的配合也很重要要 ...

  5. git在idea中的使用,如何构远程git方仓库

    git 下载:http://learning.happymmall.com/git/   配置用户名:$ git config --glob user.name "forever" ...

  6. Java——IO类 字节流概述

    body, table{font-family: 微软雅黑} table{border-collapse: collapse; border: solid gray; border-width: 2p ...

  7. KMP 详解图

  8. Tomcat 域名绑定多个Host配置要点

    一.在server.xml中添加Host节点,name就是需要绑定的域名,多个域名在Host节点下建立<Alias></Alias>子节点,可建立多个. <Engine ...

  9. 多重继承,虚继承,MI继承中虚继承中构造函数的调用情况

    先来测试一些普通的多重继承.其实这个是显而易见的. 测试代码: //测试多重继承中派生类的构造函数的调用顺序何时调用 //Fedora20 gcc version=4.8.2 #include < ...

  10. jq 的onchange事件

    按商品类型显示:<select onchange="location.href='__ACTION__/type_id/'+this.value;">    <o ...