elastic-job 分布式定时任务框架 在 SpringBoot 中如何使用(二)动态添加任务需求
之前一篇用过了如何在使用创建最简单的任务:比如每天定时清空系统的缓存
这篇文章主要讲解:如何运用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 中如何使用(二)动态添加任务需求的更多相关文章
- elastic-job 分布式定时任务框架 在 SpringBoot 中如何使用(一)初始化任务并定时执行
第一篇需要实现一个最简单的需求:某个任务定时执行,多台机子只让其中一台机子执行任务 一.安装 分布式应用程序协调服务 zookeeper,安装步骤在链接里面 Linux(Centos7)下安装 zoo ...
- 分布式定时任务框架——python定时任务框架APScheduler扩展
http://bbs.7boo.org/forum.php?mod=viewthread&tid=14546 如果将定时任务部署在一台服务器上,那么这个定时任务就是整个系统的单点,这台服务器出 ...
- Elastic-Job - 分布式定时任务框架
Elastic-Job - 分布式定时任务框架 摘要 Elastic-Job是ddframe中dd-job的作业模块中分离出来的分布式弹性作业框架.去掉了和dd-job中的监控和ddframe接入规范 ...
- 分布式定时任务框架比较,spring batch, tbschedule jobserver
分布式定时任务框架比较,spring batch, tbschedule jobserver | 移动开发参考书 分布式定时任务框架比较,spring batch, tbschedule jobser ...
- 基于spring+quartz的分布式定时任务框架
问题背景 我公司是一个快速发展的创业公司,目前有200人,主要业务是旅游和酒店相关的,应用迭代更新周期比较快,因此,开发人员花费了更多的时间去更=跟上迭代的步伐,而缺乏了对整个系统的把控 没有集群之前 ...
- 在Spring-boot中,为@Value注解添加从数据库读取properties支持
一般我们会把常用的属性放在工程的classpath文件夹中,以property,yaml或json的格式进行文件存储,便于Spring-boot在初始化时获取. @Value则是Spring一个非常有 ...
- Elastic-Job——分布式定时任务框架
摘要: Elastic-Job是ddframe中dd-job的作业模块中分离出来的分布式弹性作业框架.去掉了和dd-job中的监控和ddframe接入规范部分.该项目基于成熟的开源产品Quartz和Z ...
- Quartz小记(一):Elastic-Job - 分布式定时任务框架
Elastic-Job是ddframe中dd-job的作业模块中分离出来的分布式弹性作业框架.去掉了和dd-job中的监控和ddframe接入规范部分.该项目基于成熟的开源产品Quartz和Zooke ...
- Scheduled定时任务器在Springboot中的使用
Scheduled定时任务器是Spring3.0以后自带的一个定时任务器. 使用方式: 1.添加依赖 <!-- 添加 Scheduled 坐标 --> <dependency> ...
随机推荐
- PHP:第四章——数组中的排序函数
<pre> <?php header("Content-Type:text/html;charset=utf-8"); //1) /*sort - 对数组进行升序 ...
- ZOJ 3829 Known Notation 贪心 难度:0
Known Notation Time Limit: 2 Seconds Memory Limit: 65536 KB Do you know reverse Polish notation ...
- 如何搭建.NET Entity Framework分布式应用系统框架
一. 前言 ADO.NET Entity Framework(以下简称EF)是微软推出的一套O/RM框架,如果用过Linq To SQL的人会比较容易理解,因为Linq To ...
- git reset --hard和git revert命令
git reset --hard和git revert命令 git误操作时可以用git reset –hard 去撤销这次修改, 但是这样做也有问题,可能在之前本地有没有提交的修改也都消失了, ...
- 重置delphi Printer对象
http://www.efg2.com/Lab/Library/UseNet/1999/0714b.txt From: "Nick Ryan" <nick@avatardes ...
- Python 文件修改
# 需求: 把好人换成sb # 必须: # 1. 先从文件中读取内容 # 2. 把要修改的内容进行修改 # 3. 把修改好的内容写人一个新文件 # 4. 删除掉原来的文件 # 5. 把新文件重命名成原 ...
- 降低版本安装flashPlayer
运行regedit,打开注册表. 搜索flash,找到FlashPlayer文件夹. 打开里面的safeversions,把里面高版本的项目删除就可以了. 安装低版本的并设置不自动更新.
- SWIFT推送之本地推送(UILocalNotification)之二带按钮的消息
上一篇讲到的本地推送是普通的消息推送,本篇要讲一下带按钮动作的推送消息,先上个图瞅瞅: 继上一篇的内容进行小小的改动: 在didFinishLaunchingWithOptions方法内进行以下修改 ...
- ThinkPHP CodeIgniter URL访问举例
ThinkPHP URL访问: http://localhost/think/index.php/Home/login/func/[name/syt/password/123/] ht ...
- 安装wordcloud第三方库Unable to find vcvarsall.bat
前言 本来想要使用python爬一些数据的,制作词云,感觉挺好玩的,不过python安装第三方库的时候遇到了一些问题,有的问题比较好解决,有的就找了好久才知道怎么解决的,故记录下来. 环境 系统:wi ...