java 修改cron表达式_java – Spring Scheduler动态更改cron表达式

其实我遇到了同样的问题

我假设您需要从用户获取日期(1-31),时间,星期几,调度程序类型(每日,每月,每周).

首先,您需要从用户的给定日期时间创建cron表达式

下面的代码将创建cron表达式,它接受一个map并将cron表达式作为字符串返回.

public String getCronExp(final Map configMap) {

LOGGER.debug(">> getCronExp");

String exp = "";

final String type = (String) configMap.get(SCHEDULER_TYPE);

final String time = (String) configMap.get(TIME);

final String[] split = time.split(this.COLON);

String hour = split[0];

String min = split[1];

if ("00".equalsIgnoreCase(min)) {

min = ZERO;

}

if ("00".equalsIgnoreCase(hour)) {

hour = "0";

}

if ("daily".equalsIgnoreCase(type)) {

exp = this.ZERO + this.WHITE_SPACE + min + this.WHITE_SPACE + hour + this.WHITE_SPACE + this.ASTERISK + this.WHITE_SPACE + this.ASTERISK

+ this.WHITE_SPACE + "?";

} else if ("monthly".equalsIgnoreCase(type)) {

final String date = (String) configMap.get(START_DATE);

exp = this.ZERO + this.WHITE_SPACE + min + this.WHITE_SPACE + hour + this.WHITE_SPACE + date + this.WHITE_SPACE + this.ASTERISK + this.WHITE_SPACE

+ "?";

} else if ("weekly".equalsIgnoreCase(type)) {

final String dayOfWeek = (String) configMap.get(DAY_OF_WEEK);

exp = this.ZERO + this.WHITE_SPACE + min + this.WHITE_SPACE + hour + this.WHITE_SPACE + "?" + this.WHITE_SPACE + this.ASTERISK + this.WHITE_SPACE

+ dayOfWeek;

}

LOGGER.info("Latest cron expression scheduler " + exp);

LOGGER.debug("<< getCronExp");

return exp;

}

在我们得到cron表达式后,我们遇到了触发调度程序的问题.

创建一个扩展runnable的类:

public class Scheduler implements Runnable {

@SuppressWarnings("rawtypes")

ScheduledFuture scheduledFuture;

TaskScheduler taskScheduler ;

//this method will kill previous scheduler if exists and will create a new scheduler with given cron expression

public void reSchedule(String cronExpressionStr){

if(taskScheduler== null){

this.taskScheduler = new ConcurrentTaskScheduler();

}

if (this.scheduledFuture() != null) {

this.scheduledFuture().cancel(true);

}

this.scheduledFuture = this.taskScheduler.schedule(this, new CronTrigger(cronExpressionStr));

}

@Override

public void run(){

// task to be performed

}

//if you want on application to read data on startup from db and schedule the schduler use following method

@PostConstruct

public void initializeScheduler() {

//@postcontruct method will be called after creating all beans in application context

// read user config map from db

// get cron expression created

this.reSchedule(cronExp);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值