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

本文介绍如何在Spring 3.x中创建任务调度器,并在应用程序运行时根据用户输入动态更改cron表达式。首先,从用户处获取日期、时间和星期等信息来构建cron表达式。然后,通过实现Runnable接口并使用ScheduledFuture和ConcurrentTaskScheduler来重新调度任务,以根据新的cron表达式触发任务执行。
摘要由CSDN通过智能技术生成

I am able to create a taskScheduler in applicationContext.xml, and my job is triggered periodically based on the cron attribute.

I would like to change this cron expression(triggering period) after scheduler start, I mean while JavaEE application is running.

using Spring 3.XX

解决方案

Actually I've faced same issue

I am assuming you will need to get date(1-31) , time, day of week ,type of scheduler (Daily , monthly , weeekly ) from user.

First, you need to create cron expression from the given date time from user

Following code will create cron expression it takes an map and return cron expression as string.

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;

}

After we get cron expression we have issue of triggering the scheduler.

Create a class that extends 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
    评论
Java可以使用cron表达式来实现定时任务。cron表达式由7个时间元素组成,分别为秒、分、时、日期、月份、星期几和年份。其中,年份是可选的,一般不需要指定。Spring 4.x的Spring Task只支持前6个时间元素,而Quartz框架则支持完整的7个时间元素。 下面是一个使用Java实现定时任务的示例代码: ```java import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; public class CronScheduler { public static void main(String[] args) throws SchedulerException { // 创建调度器 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // 创建任务 JobDetail job = JobBuilder.newJob(MyJob.class).build(); // 创建触发器,使用cron表达式 Trigger trigger = TriggerBuilder.newTrigger() .withSchedule(CronScheduleBuilder.cronSchedule("0 0 12 * * ?")) // 每天中午12点执行 .build(); // 将任务和触发器绑定到调度器 scheduler.scheduleJob(job, trigger); // 启动调度器 scheduler.start(); } } public class MyJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { // 在这里写你的定时任务逻辑 System.out.println("定时任务执行了"); } } ``` 上述代码中,首先创建了一个调度器对象,然后创建了一个任务对象(实现了Job接口),并创建了一个触发器对象,通过`withSchedule`方法传入cron表达式来指定任务执行的时间。最后,将任务和触发器绑定到调度器,并启动调度器。 以上就是使用Java实现定时任务的简单示例。你可以根据需要自定义定时任务的逻辑和cron表达式来实现不同的定时功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值