Spring boot运行时添加定时任务

最近在做一个Web的时候,因为定时的时间是由需要在网站运行时动态添加定时任务.

并且所需要的定时任务还不少,且错综复杂.

一开始去网上找资料,

@Component
public class ScheduledTask {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Integer count0 = 1;
    private Integer count1 = 1;
    private Integer count2 = 1;

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() throws InterruptedException {
        System.out.println(String.format("---第%s次执行,当前时间为:%s", count0++, dateFormat.format(new Date())));
    }

    @Scheduled(fixedDelay = 5000)
    public void reportCurrentTimeAfterSleep() throws InterruptedException {
        System.out.println(String.format("===第%s次执行,当前时间为:%s", count1++, dateFormat.format(new Date())));
    }

    @Scheduled(cron = "0 0 1 * * *")
    public void reportCurrentTimeCron() throws InterruptedException {
        System.out.println(String.format("+++第%s次执行,当前时间为:%s", count2++, dateFormat.format(new Date())));
    }

}
是能用,但是着是基于注解的,一开始就要用代码写死了,很明显不符合在"运行时"添加定时任务.
package com.jege.spring.boot.task;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import com.jege.spring.boot.data.jpa.entity.User;
import com.jege.spring.boot.data.jpa.repository.UserRepository;

/**
 * 动态修改定时任务cron参数
 */
@Component
public class DynamicScheduledTask implements SchedulingConfigurer {
  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

  private static final String DEFAULT_CRON = "0/5 * * * * ?";
  private String cron = DEFAULT_CRON;

  @Autowired
  private UserRepository userRepository;

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    taskRegistrar.addTriggerTask(new Runnable() {
      @Override
      public void run() {
    if (!cron.equals(DEFAULT_CRON)) {
      User user = new User("je_ge", 20);
      userRepository.save(user);
    }
    // 定时任务的业务逻辑
    System.out.println("动态修改定时任务cron参数,当前时间:" + dateFormat.format(new Date()));
      }
    }, new Trigger() {
      @Override
      public Date nextExecutionTime(TriggerContext triggerContext) {
    // 定时任务触发,可修改定时任务的执行周期
    CronTrigger trigger = new CronTrigger(cron);
    Date nextExecDate = trigger.nextExecutionTime(triggerContext);
    return nextExecDate;
      }
    });
  }

  public void setCron(String cron) {
    this.cron = cron;
  }
}
这个也能用,我刚开始还打算采取了这个办法作为本次设计的定时任务,结果在做的过程中发现:

1.这样的定时也是在一开始就要设定的(configureTasks这个方法只会运行一次),后面没办法添加定时任务了

2.这个定时,如果你要修改定时的时间的话,前提条件是在你修改了定时时间后,这个定时任务必须运行定时方法后,才能修改定时任务.

比如在configureTask里面添加几个定时任务,是15分钟之后执行定时方法的,但是用户突然又要设置12分钟之后的时间来执行定时方法,那么就会出现这个定时任务在15分钟之后执行完定时方法之后才改变了定时时间(刚才的12分钟)

这样当然也不符合我们的需求

后面找了一个方法,代码如下:

/**
 * Created by 我码故我在 on 17-5-5.
 */
@Component
public class TestSchedule implements SchedulingConfigurer {
    private ThreadPoolTaskScheduler mScheduler = new ThreadPoolTaskScheduler(); //可以动态往里面添加定时任务
    private Map<String, ScheduledFuture> map = new HashMap<>();
    Runnable run = new Runnable() {
        @Override
        public void run() {
            //TODO:JOB
            System.out.println("MyJob");
        }
    };
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        mScheduler.initialize();
    }

    public void setScheduler(String jobName, String cronExp) {
        map.put(jobName, mScheduler.schedule(run, new CronTrigger(cronExp)));
    }
}

只要在运行时,调用testSchedule.setScheduler("MyFirstJob", "0 0 1 1,7 * ? ");cron表达式换成所需要的就好,就可以把定时任务添加进去,等待执行定时方法.

引用:

第一个代码段

第二个代码段

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值