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

这篇文章主要讲解:如何运用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. PHP:第四章——PHP数组添加,删除,插入,分割,合并,及运算符

    <pre> <?php header("Content-Type:text/html;charset=utf-8"); /*知识点一:赋值运算符 = 代码示例:数 ...

  2. UVALive 6320

    .............先让我哭一会....... 因为样例三.... 没敢敲...然后确实是样例错了...然后...上次比赛刚做过的一道类似的题...URAL 1941...大水题啊......悔 ...

  3. learning shell script prompt to run with superuser privileges (4)

    Shell script prompt to run with superuser privileges [Purpose]        Check whether have root privil ...

  4. 第一章连通性问题-----algorithm in C 读书笔记

    首先不得不吐槽一下翻译的质量,霍红卫....你给我站出来,不打死你,只想问你一下,你当年四级过了吗? 问题描述 输入两个整数,代表两个节点,如果这两个整数没有建立连接(这包括直接连接和通过其他节点连接 ...

  5. MyEclipse WebSphere开发教程:安装和更新WebSphere 6.1, JAX-WS, EJB 3.0(三)

    MyEclipse超值折扣 限量 100 套! 立即开抢>> [MyEclipse最新版下载] MyEclipse支持Java EE技术(如JAX-WS和EJB 3.0),它们以功能包的形 ...

  6. css background url 路径

    刚刚碰到一个奇怪的问题,这样一段CSS代码: 1 .pho6 { background: url(img/pho6.jpg);  } 这段代码居然不能显示出背景图片,路经绝对是没错的代码肯定没有问题, ...

  7. 技术揭秘“QQ空间”自动转发不良信息

    大家经常会看到QQ空间自动转发一些附带链接的不良信息,即便我们的QQ密码并没有被盗取.最近通过对一个QQ空间自动转发链接进行分析,发现该自动转发机制通过利用腾讯网站存在漏洞的页面,精心构造出利用代码获 ...

  8. Ubuntu 16.04 安装 PyCharm

    https://blog.csdn.net/zhuanshu666/article/details/73554885

  9. A+B for Input-Output Practice (IV)

    A+B for Input-Output Practice (IV) Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768  ...

  10. 搭建一个SVN

    1--------------------------------------首先需要下载SVN---------------------------------------------------- ...